javascript 使用 jQuery 创建一个新属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12949645/
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
Creating a new attribute with jQuery
提问by ThinusP
Possible Duplicate:
jQuery .attr retrieving custom attribute returns undefined
I've got a weird problem, but I'm hoping I'm just doing something stupid. I'm trying to create a new attribute on an <img>
element using jQuery, and this line:
我有一个奇怪的问题,但我希望我只是在做一些愚蠢的事情。我正在尝试<img>
使用 jQuery在元素上创建一个新属性,这一行:
$(selector).attr('selected', 'no');
When I inspect the DOM in Chrome, I just see selected="selected", no matter what I set the value to.
当我在 Chrome 中检查 DOM 时,我只看到 selected="selected",无论我将值设置为什么。
Just some extra info: I can't use just boolean values, as I need to keep track of "Yes", "No" and "Partial" property values. I'm calling a JS function from the "onClick" event of the img itself, and passing this
as a parameter. I've inspected the object in the method, and the right object is passed; the fact that the attribute is set (even if to the wrong value) also supports this.
只是一些额外的信息:我不能只使用布尔值,因为我需要跟踪“是”、“否”和“部分”属性值。我从 img 本身的“onClick”事件调用一个 JS 函数,并this
作为参数传递。我已经检查了方法中的对象,并且传递了正确的对象;设置属性的事实(即使设置了错误的值)也支持这一点。
I'm dead certain I'm doing something stupid here... Any advice would be appreciated.
我已经死了,我在这里做一些愚蠢的事情......任何建议将不胜感激。
回答by Christofer Eliasson
Selected is already an attribute in the HTML standard, so you cannot create a custom attribute with the same name. In that case, you should use the data-
attributes instead and create an attribute data-selected
for instance.
Selected 已经是 HTML 标准中的一个属性,因此您不能创建具有相同名称的自定义属性。在这种情况下,您应该改用data-
属性并创建一个属性data-selected
。
In jQuery you handle the custom data attributes using the .data()
method.
在 jQuery 中,您使用.data()
方法处理自定义数据属性。
The custom data attributes are described in the HTML5 spec here.
自定义数据属性在此处的 HTML5 规范中进行了描述。
回答by Fabrizio Calderan
you could insert a data-*
custom attribute like so
你可以data-*
像这样插入一个自定义属性
$(selector).data('selected', 'no');
your element will set a data-selected
attribute
您的元素将设置一个data-selected
属性
回答by Barmar
If you need to attach arbitrary data to an element, use .data()
, not .attr()
.
如果需要将任意数据附加到元素,请使用.data()
,而不是.attr()
。
回答by Florian Margaine
A DOM property is different than a DOM attribute ;)
DOM 属性不同于 DOM 属性;)
I'd suggest using $(selector).data()
for your use case.
我建议$(selector).data()
用于您的用例。