jquery函数用于同一类的多个按钮事件

jquery function for multiple button event with same class

本文关键字:一类 事件 按钮 用于 函数 jquery      更新时间:2023-09-26

$(document).ready(function() {
  $(".like").click(function() {
    var newValue = parseInt($(".no-like").text()) + 1;
    alert(newValue);
    $(".no-like").html(newValue);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="like" data-creation-id="1069347886434951" data-id="1" href="#">
 <span class="no-like">35</span> 
</a>
<a class="like" data-creation-id="1069347886434951" data-id="1">
  <span class="no-like">3</span>
  <span class="glyphicon glyphicon-heart"></span>
</a>
<a href="">hey</a>

这里有多个按钮。每次单击它时,您需要添加1个值。例如:35到36和3到4。Jquery必须选择每个具有相应值的按钮。但即使是一个按钮,代码也不起作用。

只需使用'this'关键字来引用元素的当前实例

$(document).ready(function() {
  $(".like").click(function() {
    var newValue = +$(this).text() + 1;
    if($(this).find('.no-like').length)
      $(this).find('.no-like:eq(0)').text(newValue);
    else
      $(this).text(newValue);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="like" data-creation-id="1069347886434951" data-id="1" href="#">
 35  
</a>
<a class="like" data-creation-id="1069347886434951" data-id="1">
  <span class="no-like">3</span>
  <span class="glyphicon glyphicon-heart"></span>
</a>

$(document).ready(function() {
  $(".like").click(function() {
    var newValue = parseInt($(this).text()) + 1;//use this context for clicked element
    alert(newValue);
    $(".no-like").html(newValue);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="like" data-creation-id="1069347886434951" data-id="1" href="#">
 35
  
</a>
<a class="like" data-creation-id="1069347886434951" data-id="1">
  <span class="no-like">3</span>
  <span class="glyphicon glyphicon-heart"></span>
</a>
<a href="">hey</a>

使用此上下文

您必须使用$(this)从同一元素获取。

$(document).ready(function() {
  $(".like").click(function() {
    var newValue = parseInt($(this).text()) + 1;
    alert(newValue);
    $(".no-like").html(newValue);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<a class="like" data-creation-id="1069347886434951" data-id="1" href="#">
 35
  
</a>
<a class="like" data-creation-id="1069347886434951" data-id="1">
  <span class="no-like">3</span>
  <span class="glyphicon glyphicon-heart"></span>
</a>
<a href="">hey</a>