Javascript 使用 jquery 为数据属性动态设置值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7163234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:07:24  来源:igfitidea点击:

Setting a value dynamically for data attributes using jquery

javascriptjqueryjquery-data

提问by Abishek

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?

我广泛使用数据属性来管理客户端事件中的数据。是否可以使用 javascript 或 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:

上面的javascript代码抛出错误:

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

“未捕获的 ReferenceError:赋值中的左侧无效”。

Could someone please tell me how this can be achieved?

有人可以告诉我这是如何实现的吗?

回答by jjeaton

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

我相信上面的答案只会在 jQuery 中的那个元素上设置数据对象。

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

如果你需要设置实际的 HTML data-* 属性,你需要使用这个:

$(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.

也要注意以这种方式检索 HTML5 data-* 属性,尽管您可以使用快捷方式$(this).data("class_value");检索它们,但后续检索将使用 jQuery 数据对象中的缓存值。

From the jQuery docs:

来自jQuery 文档

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).

数据属性在第一次访问数据属性时被拉取,然后不再访问或改变(然后所有数据值都存储在 jQuery 内部)。

Source: jQuery caching of data attributes

来源:jQuery 缓存数据属性

回答by Dogbert

You need to do

你需要做

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

回答by Rafay

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

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

.data

.data