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

javascript - Setting a value dynamically for data attributes using jquery

I use data attributes extensively for managing data in client side events. Is it possible to assign value dynamically to a data attribute using javascript or jquery?

<li data-class_value="somevalue" class="myclass"></li>


$('.myclass').click(function(){
   $(this).data('class_value') = "new value";
});

The above javascript code throws the error:

"Uncaught ReferenceError: Invalid left-hand side in assignment".

Could someone please tell me how this can be achieved?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I believe the answers above would only set the data object on that element within jQuery.

If you need to set the actual HTML data-* attribute, you'd need to use this:

$(this).attr("data-class_value", "new value");

Beware of retrieving HTML5 data-* attributes this way as well, as although you can use the shortcut $(this).data("class_value"); to retrieve them, subsequent retrievals will use the cached value in the jQuery data object.

From the jQuery docs:

The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).

Source: jQuery caching of data attributes


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

1.4m articles

1.4m replys

5 comments

56.9k users

...