简体   繁体   中英

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

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. 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?

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.

As such, you need to update using .data() if you want the next "get" to fetch the updated value.

$('.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 ).

$('.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.

  1. Try using the same method for both getting and setting the data attribute (either .attr or .data )
  2. Avoid use of implicitly declared global variables by placing var in front of id .

So your code should look like this:

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

Demonstration

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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