提问者:小点点

如何用jquery在循环中更改每个按钮的值


我有很多follow按钮,每个按钮都与一个特定用户链接。 现在,当用户单击按钮时,对于在div中单击的每个按钮,它应该从follow更改为follow

我尝试使用以下方法来实现这一点:

   $(document).ready(function(){
  $('.msg-action').each(function(){
   $("#follow-button2").click(function(){
    if ($("#follow-button2").text().trim() == "Follow"){
        $("#follow-button2").text('Following');

    }else{
        $("#follow-button2").text('Follow');

   }
   });
   });
 });

但似乎不起作用。 如果我这样做:

  $(document).ready(function(){

   $("#follow-button2").click(function(){
    if ($("#follow-button2").text().trim() == "Follow"){
        $("#follow-button2").text('Following');

    }else{
        $("#follow-button2").text('Follow');

   }
  });
  });

只有按钮的第一个实例会被更改,其他的不会,因为jquery理解我所提到的类或id的第一个实例。

我的HTML代码:

while($row3 = $query->fetch())
 {


  ?>
    <div Class="inside-card" 
                <td>
        <div class="msg-body">
        </a>
            </img>

                <div class="msg-action">

        <form method="POST" action='' name="followForm">

        <button  id="follow-button2" class='msg-icon' name="follow" type="submit" value="follow" onclick=""><span id="follow_id">Follow</span>  
            <input  type="hidden" value="<?php echo $follower_username; ?>" name="follow_id"/>
        </button>

 ?>

那么有没有一种方法可以使用jquery来更改每个点击的按钮呢?


共3个答案

匿名用户

在每个按钮中添加此span

 <span style="display:none">Following</span>

将按钮的id更改为class类似

      // your while loop starts
      // add this as your button in your while loop
      <button  class="follow-button" class='msg-icon' name="follow" type="submit" value="follow" ><span id="follow_id">Follow</span>  
        <input  type="hidden" value="<?php echo $follower_username; ?>" name="follow_id"/>
        <span style="display:none">Following</span>
    </button>

     // your loop ends

并添加此js

$('.follow-button').click(function(){


  $(this).find('span').toggle();

});

这是jsfiddle,经过测试,100%正确工作。

匿名用户

在循环中,您正在迭代父元素,但实际上使用以下方法调用单个子元素:

$("#follow-button2").text('Following');

如果要使用id=“Follow-Button2”访问每个元素,则必须迭代子选择器并使用$(this)内部访问它。 尝试如下所示:

$("#follow-button2").each(function(index) {
    // the context changed => use $(this) to access each element
    if ($(this).text().trim() == "Follow"){
        $(this).text('Following');

    }else{
        $(this).text('Follow');
   }
});

匿名用户

首先,获取所有follow按钮,并创建一个数组,以便于对集合进行迭代。

const followButtonClass = "msg-action";
const getFollowButtonsByClass = (className) => document.getElementsByClassName(className);
const followButtons = [...getFollowButtonsByClass(followButtonClass)];

然后将事件附加到每个follow按钮,以便在有人单击它时更改文本。

const followToggleHandler = (event) => 
   event.target.textContent === "Follow" ?
   event.target.textContent = "Following" : 
   event.target.textContent = "Follow"; // This will change to follow again when user clicks again

followButtons.forEach(x => {
    x.addEventListener("click", followToggleHandler);
})