简体   繁体   中英

Update value of data-attr in jQuery

I need to update a data-attr every time user clicks on a btn. But its not working how it should. Here is a demo code:

$('div.wrapper').on('click', 'div.btn', function(){
    var thisGuy = $(this),
        offset = thisGuy.data('showreplies');
    thisGuy.attr('data-showreplies', parseInt(offset) + 10);
    $('div.dataAttr').show().text(thisGuy.data('showreplies'));
});

Here is the DOM:

<div class="wrapper">
    <div class='btn' data-showreplies='10'>Click Me</div>
</div>
<div class="dataAttr"></div>

What i wanted to do is that when a user will click on the btn then the value of the data-showreplies attr will be incremented to 10 and then it will display the updated value inside the div.dataAttr, for every click it will do the incrementation.

JsFiddle Link: https://jsfiddle.net/hasantg/knwpdw42/6/

try to change

 thisGuy.attr('data-showreplies', parseInt(offset) + 10);

to

 thisGuy.data('showreplies', parseInt(offset) + 10);

The data function can also be used as a setter:

$('div.wrapper').on('click', 'div.btn', function(){
        var thisGuy = $(this),
        offset = thisGuy.data('showreplies');
        thisGuy.data('showreplies', parseInt(offset) + 10);
        $('div.dataAttr').show().text(thisGuy.data('showreplies'));
});

Note that the attribute in the DOM stays 10, because jQuery has an internal cache for data values.

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