Setting a value dynamically for data attributes using jquery

梦想的初衷 提交于 2019-12-17 16:19:32

问题


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?


回答1:


You need to do

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



回答2:


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




回答3:


$(this).data('class_value','new value') ;

.data



来源:https://stackoverflow.com/questions/7163234/setting-a-value-dynamically-for-data-attributes-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!