Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

jquery - Can't update data-attribute value

Although there are some examples of this on the web, it does not seem to work correctly. I can't figure out the problem.

I have this simple HTML

<div id="foo" data-num="0"></ div>
<a href="#" id="changeData">change data value</a>

Every time I click the link "change data value" I want to update the data value of data-num. For example, I need it to be 1,2,3,4,... (plus 1 every time I click the link)

what I have is

var num = $('#foo').data("num");
console.log(num);
num = num+1;               
console.log(num);
$('#foo').attr('data-num', num);   

The value changes one time from 0 to 1 every time. I can't make it incremental. Any suggestions on what I'm doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use that instead, if you wish to change the attribute data-num of node element, not of data object:

DEMO

$('#changeData').click(function (e) { 
    e.preventDefault();
    var num = +$('#foo').attr("data-num");
    console.log(num);
    num = num + 1;
    console.log(num);
    $('#foo').attr('data-num', num);
});

PS: but you should use the data() object in virtually all cases, but not all...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...