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
689 views
in Technique[技术] by (71.8m points)

jquery set data attr

Html

<div id="you" data-you="Hello mean">super</div>

is #you html element change data-you attribute

console.log($("#you").data("you")); // Hello mean

$("#you").attr("data-you", "yes change you atribute");

console.log($("#you").data("you")); // Hello mean | does not change.

Attribute "data-you" does not change when I change. How can I do this?

thank you.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

There has already been an answer chosen as a correct one, however its seems like none of the answers clearly and concisely explain what is happening.
So let me give this a shot:

$(element).data(key, value) does not change the html5 'data-*' attributes of the element, jQuery internally stores the key-value (in jQuery.cache).
As a result when you call $(element).data(key) you get what is stored internally by jQuery.

To answer your question here:

Since you are looking to change the data-you attribute of your html tag you will instead need to use the attr() method

Thus:

console.log($("#you").attr("data-you")); // Hello mean

$("#you").attr("data-you", "yes change you atribute");

console.log($("#you").attr("data-you")); // The data-you attribute has been changed.

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

...