【问题标题】:Issue with Javascript in Posting system发布系统中的 Javascript 问题
【发布时间】:2022-01-10 04:38:04
【问题描述】:

所以,我有一个发布系统。当您在输入字段中键入帖子并单击提交按钮时,帖子会在 PHP 和 AJAX 的帮助下显示。

现在该帖子上有点赞按钮和评论按钮之类的东西,当您点击点赞按钮时,它会变成蓝色。现在,在发表帖子并显示帖子后,单击“赞”按钮将使其变为蓝色。但是,假设您再发一个帖子。对于该帖子,一切正常,除了当您单击第二个或第三个帖子上的“赞”按钮时,它会使第一个帖子上的“赞”按钮仅变为蓝色,与评论按钮类似。此外,第一个帖子的背景颜色为银色 (#C0C0C0),但是任何其他帖子,如第二个或第三个帖子,都没有。它们没有背景颜色。

这些东西(点击时变成蓝色)是使用 JavaScript 完成的。我从中确定的是,除了第一篇文章之外,JS 不适用于任何其他文章。为了解决这个问题,我尝试更改代码中 JS 的位置,因为我认为它与范围有关,但事实并非如此。请帮忙解决 JS 和背景颜色问题。

PHP/HTML/CSS 代码:

<style>
.textPost {
  margin-top: 170px;
  width: 650px;
  height: 400px;
  position: fixed;
  background-color: #C0C0C0;
  margin-left: 685px;
  border-radius: 15px;
}

.textpostFormat {
  margin-left: -640px;
  position: fixed;
}
</style>

<div class="textPost">
  <?php

  $sql = "SELECT * FROM posts";
  $result = mysqli_query($connection, $sql);
  if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {

  ?>
  <div class="textpostFormat" id="textpostFormat">
          <img src="img/pfp.png" alt="pfp" onclick="location.href='profile.php'" class="textpostPFP">
    <b><div class="textinfo"><?php echo $firstname . "&nbsp;" . $lastname ?></div></b>
    <img src="img/options.png" alt="textpostOptions" class="textpostOptions">
    <hr style="margin-top: 85px; width: 600px; position: fixed; margin-left: 663px; border:1px solid black; border-radius: 10px">
    <hr style="margin-top: 200px; width: 600px; position: fixed; margin-left: 663px; border:1px solid black; border-radius: 10px">
    <div class="textfeedbackBar" style="position: fixed">
      <hr style="margin-top: 250px; width: 600px; position: fixed; margin-left: 663px; border: 1px solid black; border-radius: 10px">
      <div class="textratingBar">
        <div style="float: left; margin: 10px; cursor: pointer">1</div>
        <hr style="width: 0px; height: 43px; float: left; margin-top: -2px; border: 1px solid black">
        <div style="float: left; margin: 10px; cursor: pointer">2</div>
        <hr style="width: 0px; height: 43px; float: left; margin-top: -2px; border: 1px solid black">
        <div style="float: left; margin: 10px; cursor: pointer">3</div>
        <hr style="width: 0px; height: 43px; float: left; margin-top: -2px; border: 1px solid black">
        <div style="float: left; margin: 10px; cursor: pointer">4</div>
        <hr style="width: 0px; height: 43px; float: left; margin-top: -2px; border: 1px solid black">
        <div style="float: left; margin: 10px; cursor: pointer">5</div>
        <hr style="width: 0px; height: 43px; float: left; margin-top: -2px; border: 1px solid black">
        <div style="float: left; margin: 10px; cursor: pointer">6</div>
        <hr style="width: 0px; height: 43px; float: left; margin-top: -2px; border: 1px solid black">
        <div style="float: left; margin: 10px; cursor: pointer">7</div>
        <hr style="width: 0px; height: 43px; float: left; margin-top: -2px; border: 1px solid black">
        <div style="float: left; margin: 10px; cursor: pointer">8</div>
        <hr style="width: 0px; height: 43px; float: left; margin-top: -2px; border: 1px solid black">
        <div style="float: left; margin: 10px; cursor: pointer">9</div>
        <hr style="width: 0px; height: 43px; float: left; margin-top: -2px; border: 1px solid black">
        <div style="float: left; margin-left: 275px; cursor: pointer; margin-top: 10px; position: fixed">10</div>
      </div>
    </div>
    <hr style="margin-top: 320px; width: 600px; position: fixed; margin-left: 663px; border: 1px solid black; border-radius: 10px">
    <img src="img/pfp.png" alt="commentpfp" onclick="location.href='profile.php'" class="textcommentPFP">
    <input type="text" name="textComment" class="textComment" id="textComment" placeholder="Write a comment">
    <p style="margin-left: 670px; margin-top: 95px; position: fixed; font-size: 45px; font-family: 'Rajdhani'"><?php echo $row["body"]; ?></p>
    <div class="textPostData" style="position:fixed; font-family: 'Rajdhani'; margin-left: 820px; margin-top: 150px">
      <h4 id="textDataLikes" style="cursor: pointer">0 Likes</h4>
      <h4 id="textDataComments" style="margin-left: 102px; margin-top: -42px; cursor: pointer">0 Comments</h4>
      <h4 id="textDataReactions" style="margin-left: 240px; margin-top: -42px; cursor: pointer">0 Reactions</h4>
    </div>
    <div style="margin-left: 715px; position: fixed; font-family: 'Rajdhani'">
      <h2 style="margin-top: 206px; margin-left: -30px; cursor:pointer; padding: 5px; position: fixed" class="textLike" id="textLike" onclick="textLikeClick()"><i class="fa fa-thumbs-up"></i> Like</h2>
      <h2 style="margin-left: 99px; margin-top: 206px; cursor:pointer; padding: 5px; position: fixed" class="makeComment" id="makeComment" onclick="textCommentClick()"><i class="fa fa-comment" style="margin-top: 2px;"></i> Comment</h2>
      <h2 style="margin-left: 290px; margin-top: 206px; cursor:pointer; padding: 5px; position: fixed" class="textReact" id="textReact"><i class="fa fa-smile" style="margin-top: 2px;"></i> React</h2>
      <h2 style="margin-left: 432px; margin-top: 206px; cursor:pointer; padding: 5px; position: fixed" class="textShare" id="textShare"><i class="fa fa-share" style="margin-top: 2px"></i> Share</h2>
    </div>
  </div>
  <div style="margin-left: 398px; margin-top: 236px">
    <img class="textupvote" id="textUpvoteImg" src="img/upvote.png" alt="upvote" onclick="changetextUpvote()" style="width: 100px; margin-bottom: 28px; cursor: pointer">
    <img class="textdownvote" id="textDownvoteImg" src="img/downvote.png" alt="downvote" onclick="changetextDownvote()" style="width: 55px; margin-top: 32px; margin-left: 21px; position: fixed; cursor: pointer">
  </div>
  <?php

  }
}

  ?>
  </div>
  <?php

  }
}

  ?>
</div>

AJAX 代码(显示帖子而不刷新页面):

function makePost() {
  var postContent = $("#postContent").val();
  if (postContent.length > 0) {
    jQuery.ajax({
      url:"yourposts.php",
      data:{
        postContent: postContent
      },
      type:"POST",
      success:function(data){
        if (data == "success") {
          $("#textpostFormat").html(postContent);
        }
      }
    });
  }
}

Javascript 代码(用于变成蓝色按钮之类的东西):

<script type="text/javascript">

function changetextUpvote() {
  var textUpvoteImg = document.getElementById('textUpvoteImg');
  if (textUpvoteImg.src.match("orangeupvote")) {
    textUpvoteImg.src = "img/upvote.png";
  } else {
    textUpvoteImg.src = "img/orangeupvote.png";
    textDownvoteImg.src = "img/downvote.png";
  }
}

function changetextDownvote() {
  var textDownvoteImg = document.getElementById('textDownvoteImg');
  if (textDownvoteImg.src.match("orangedownvote")) {
    textDownvoteImg.src = "img/downvote.png";
  } else {
    textDownvoteImg.src = "img/orangedownvote.png";
    textUpvoteImg.src = "img/upvote.png";
  }
}

function textLikeClick() {
  document.getElementById('textLike').style.color = "blue";
}

function textCommentClick() {
  document.getElementById('textComment').focus();
}

</script>

【问题讨论】:

  • 您在循环中使用相同的 ID 值 (id="textpostFormat")。 ID 在文档中必须是唯一的
  • 那我该怎么办?我在哪里更改ID?在 HTML 中的
    中?还是在 AJAX 中?
  • 只添加// all the post content (like, comment buttons, etc.)没有帮助~请添加准确反映标记的实际内容
  • 我试图理解@Phil 所说的内容。你能帮我解决这个问题吗?
  • 每个 ID 都必须是唯一的 - 否则它就不是真正的身份。当您在整个(循环中)重复相同的 ID 时,Javascript 不知道您在调用 document.getElementById 时实际指的是哪个元素 - 它应该是第一个,最后一个,中间吗?一种方法是使用event(即:click event)并从中查找元素

标签: javascript php html jquery


【解决方案1】:

这里的所有元素都没有 ID 属性。元素的识别是基于检查 event.target 并使用querySelectorparentNode 和其他技术(例如nextElementSibling 等)在 DOM 中导航来完成的

所有按钮都注册了一个事件监听器,该事件监听器基于 data-set 属性分叉逻辑。

document.querySelectorAll('[type="button"]').forEach(bttn=>bttn.addEventListener('click',function(e){
  
  let img=this.parentNode.querySelector('img');
  let text=this.parentNode.querySelector('textarea');
  
  switch(this.dataset.action){
    case 'upvote':
      img.src='img/orangeupvote.png';
      img.classList.toggle(this.dataset.action)
    break;
    case 'downvote':
      img.src='img/orangedownvote.png';
      img.classList.toggle(this.dataset.action)
    break;
    case 'comment':
      text.focus();
      
      let fd=new FormData();
          fd.set('comment',text.value);
          
      fetch('yourposts.php',{method:'post',body:fd})
          .then(r=>r.text())
          .then(text=>{alert(text)})
    break;
    case 'like':
      this.classList.toggle('liked')
    break;
  }
}));
.liked{background:blue;color:white}
textarea:focus{background:pink}
.upvote{outline:2px solid green}
.downvote{outline:2px solid red}
<div class="textPost">
  <!--
  <?php

    $sql = "SELECT * FROM posts";
    $result = mysqli_query($connection, $sql);
    if (mysqli_num_rows($result) > 0) {
      while ($row = mysqli_fetch_assoc($result)) {

  ?>
 -->
  <h1>Example data</h1>
  <div class="textpostFormat">
    <p>Lorem ipsum dolor solit...etc #1</p>
    <img />
    <input type='button' class='usr-interaction' data-action='upvote' value='Upvote' />
    <input type='button' class='usr-interaction' data-action='downvote' value='Downvote' />
    <textarea cols=50 rows=5>This is simply a comment...</textarea>
    <input type='button' class='usr-interaction' data-action='comment' value='Comment' />
    <input type='button' class='usr-interaction' data-action='like' value='Like' />
  </div>

  <div class="textpostFormat">
    <p>Lorem ipsum dolor solit...etc #2</p>
    <img />
    <input type='button' class='usr-interaction' data-action='upvote' value='Upvote' />
    <input type='button' class='usr-interaction' data-action='downvote' value='Downvote' />
    <textarea cols=50 rows=5>Also a simple comment...</textarea>
    <input type='button' class='usr-interaction' data-action='comment' value='Comment' />
    <input type='button' class='usr-interaction' data-action='like' value='Like' />
  </div>
  
  <div class="textpostFormat">
    <p>Lorem ipsum dolor solit...etc #3</p>
    <img />
    <input type='button' class='usr-interaction' data-action='upvote' value='Upvote' />
    <input type='button' class='usr-interaction' data-action='downvote' value='Downvote' />
    <textarea cols=50 rows=5>Guess what this is...</textarea>
    <input type='button' class='usr-interaction' data-action='comment' value='Comment' />
    <input type='button' class='usr-interaction' data-action='like' value='Like' />
  </div>





</div>

【讨论】:

  • 嘿,我不太明白你的回答。真的,我只是想让您回答@Phil 的意思,他说“您在循环中使用相同的 ID 值 (id="textpostFormat")。ID 在文档中必须是唯一的。”
  • 那句话中有什么难以理解的地方?文档中的每个 ID必须是唯一的 - 它不能重复。建议您出于代码的目的忽略 ID,并使用其他方法来识别 DOM 元素 - 正如我在此处展示的那样。
  • 我在哪里重复了?我在哪里更改它?
  • 在您的 while 循环中,您有 &lt;div class="textpostFormat" id="textpostFormat"&gt; 并且根据 javascript 代码判断,还有其他重复的 ID,但您在请求时未能显示实际标记,所以除了您之外没有人知道 thigs 是什么/在哪里除此处指示的内容外重复
  • 好的,你帮我确定了我需要改变的地方。现在,我需要改变什么?
【解决方案2】:

剥离所有可怕的内联样式并用 ID 属性替换,在这种情况下,简单地使用 data-id 属性来生成一些示例渲染标记,如下所示。这并不打算成为您的最终解决方案 - 您需要了解如何将您的功能融入其中,因为坦率地说,给出的代码是混乱的。

在单击处理函数中,如果您将event 作为参数提供给该函数,则您可以在该函数中访问event.targetevent.target 指向启动点击的元素。从那时起,您可以使用 DOM 导航技术来查找其他感兴趣的节点。

document.querySelectorAll('.textpostFormat *[data-id]').forEach(n=>n.addEventListener('click',function(e){
  switch( this.dataset.id ){
    case 'textUpvoteImg':
      changetextUpvote(e);
    break;
    case 'textDownvoteImg':
      changetextDownvote(e)
    break;
    case 'makeComment':
      textCommentClick(e);
    break;
    case 'textLike':
      textLikeClick(e);
    break;
  }
}));



function changetextUpvote(e) {
    alert(e.target)
}

function changetextDownvote(e) {
  alert(e.target)
}

function textLikeClick(e) {
  alert(e.target)
}

function textCommentClick(e) {
  alert(e.target)
}
<div class='textpostFormat'>
    <a href='profile.php'><img src='img/pfp.png' alt='pfp' class='textpostPFP'></a>
    <div class='textinfo'><b>FIRSTNAME LASTNAME #1</b></div>
    <img src='img/options.png' class='textpostOptions' />

    <div class='textfeedbackBar'>
        <div class='textratingBar'>
            <div>1</div>
            <div>2</div>
            <div>3</div>
            <div>4</div>
            <div>5</div>
            <div>6</div>
            <div>7</div>
            <div>8</div>
            <div>9</div>
            <div>10</div>
        </div>
    </div>

    <a href='profile.php'><img src='img/pfp.png' alt='commentpfp' class='textcommentPFP' /></a>
    <input type='text' name='textComment' class='textComment' data-id='textComment' placeholder='Write a comment' />

    <p>PARAGRAPH - BODY CONTENT #1</p>
    <div class='textPostData'>
        <h4 data-id='textDataLikes'>0 Likes</h4>
        <h4 data-id='textDataComments'>0 Comments</h4>
        <h4 data-id='textDataReactions'>0 Reactions</h4>
    </div>
    <div>
        <h2 class='textLike' data-id='textLike'><i class='fa fa-thumbs-up'></i> Like</h2>
        <h2 class='makeComment' data-id='makeComment'><i class='fa fa-comment' style='margin-top: 2px;'></i> Comment</h2>
        <h2 class='textReact' data-id='textReact'><i class='fa fa-smile' style='margin-top: 2px;'></i> React</h2>
        <h2 class='textShare' data-id='textShare'><i class='fa fa-share' style='margin-top: 2px'></i> Share</h2>
    </div>
    <div>
        <img class='textupvote' data-id='textUpvoteImg' src='img/upvote.png' alt='upvote' />
        <img class='textdownvote' data-id='textDownvoteImg' src='img/downvote.png' alt='downvote' />
    </div>
</div>


<div class='textpostFormat'>
    <a href='profile.php'><img src='img/pfp.png' alt='pfp' class='textpostPFP'></a>
    <div class='textinfo'><b>FIRSTNAME LASTNAME #2</b></div>
    <img src='img/options.png' class='textpostOptions' />

    <div class='textfeedbackBar'>
        <div class='textratingBar'>
            <div>1</div>
            <div>2</div>
            <div>3</div>
            <div>4</div>
            <div>5</div>
            <div>6</div>
            <div>7</div>
            <div>8</div>
            <div>9</div>
            <div>10</div>
        </div>
    </div>

    <a href='profile.php'><img src='img/pfp.png' alt='commentpfp' class='textcommentPFP' /></a>
    <input type='text' name='textComment' class='textComment' data-id='textComment' placeholder='Write a comment' />

    <p>PARAGRAPH - BODY CONTENT #2</p>
    <div class='textPostData'>
        <h4 data-id='textDataLikes'>0 Likes</h4>
        <h4 data-id='textDataComments'>0 Comments</h4>
        <h4 data-id='textDataReactions'>0 Reactions</h4>
    </div>
    <div>
        <h2 class='textLike' data-id='textLike'><i class='fa fa-thumbs-up'></i> Like</h2>
        <h2 class='makeComment' data-id='makeComment'><i class='fa fa-comment' style='margin-top: 2px;'></i> Comment</h2>
        <h2 class='textReact' data-id='textReact'><i class='fa fa-smile' style='margin-top: 2px;'></i> React</h2>
        <h2 class='textShare' data-id='textShare'><i class='fa fa-share' style='margin-top: 2px'></i> Share</h2>
    </div>
    <div>
        <img class='textupvote' data-id='textUpvoteImg' src='img/upvote.png' alt='upvote' />
        <img class='textdownvote' data-id='textDownvoteImg' src='img/downvote.png' alt='downvote' />
    </div>
</div>

【讨论】:

  • 我们可以参加谷歌会议来解决这个问题吗?这对你和我来说都会更容易。
猜你喜欢
相关资源
最近更新 更多
热门标签