简体   繁体   English

页面中的data-id更改后,如何在jQuery中选择data-id?

[英]How to select data-id in jQuery after the data-id is changed in the page?

http://jsfiddle.net/V76T7/ http://jsfiddle.net/V76T7/

 $('.click').click(function() {
  id = $(this).data('id');
  alert(id);
  $('.click').attr('data-id' , id+1);
 });

As shown in the link, I want the data-id to increase by 1 each time I click the button. 如链接中所示,我希望每次单击按钮时data-id都增加1。 The data-id did indeed increase to 2 when you click it and you can see it using 'Inspect Element" in Chrome. But the next time I click on it, the popup is still 1, but not "2" as expected. Why? 当您单击它时,data-id确实确实增加到了2,并且可以在Chrome中使用“检查元素”看到它。但是,当我下次单击它时,弹出窗口仍然是1,而不是预期的“ 2”。 ?

Since you're using .data to get the value, it'll be imported into jQuery.cache , so future .data() fetches will come from there instead of from the attribute. 由于您正在使用.data来获取值,因此它将被导入jQuery.cache ,因此将来的.data()获取将从那里而不是从属性开始。

As such, you need to update using .data() if you want the next "get" to fetch the updated value. 因此,如果要下一个“获取”来获取更新的值,则需要使用.data()更新。

$('.click').click(function() {
    id = $(this).data('id');
    alert(id);
    $('.click').data('id' , id+1);
});

Or better, just use .attr() since it's faster, and has less memory overhead (since the value isn't duplicated in jQuery.cache ). 或更好的方法是,只需使用.attr()因为它更快,并且具有较少的内存开销(因为该值在jQuery.cache不重复)。

$('.click').click(function() {
    id = $(this).attr('data-id');
    alert(id);
    $('.click').attr('data-id' , id+1);
});

I'd suggest only using .data() for this if you need to retain the original, or if you're working with more complex objects like those created from a JSON value. 我建议仅在需要保留原始数据或正在处理更复杂的对象(如从JSON值创建的对象.data()时才使用.data()

  1. Try using the same method for both getting and setting the data attribute (either .attr or .data ) 尝试使用相同的方法来获取和设置数据属性( .attr.data
  2. Avoid use of implicitly declared global variables by placing var in front of id . 通过将var放在id前面,避免使用隐式声明的全局变量。

So your code should look like this: 因此,您的代码应如下所示:

$('.click').click(function() {
     var id = $(this).data('id');
     alert(id);
     $(this).data('id', id+1);
});

Demonstration 示范

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM