Javascript 在 JQuery 中选择自定义数据属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11759358/
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
Selecting custom data attributes in JQuery
提问by user962206
I have a list here
我这里有一份清单
<ul id="demo2" data-name="demo2">
<li data-value="here">here</li>
<li data-value="are">are</li>
<li data-value="some...">some</li>
<!-- notice that this tag is setting a different value :) -->
<li data-value="initial">initial</li>
<li data-value="tags">tags</li>
</ul>
Where each li item has a custom data attribute. On JQuery how would get all of the values of each li element which has an attribute of data-value? I want to get their value.
其中每个 li 项目都有一个自定义数据属性。在 JQuery 上,如何获取每个具有 data-value 属性的 li 元素的所有值?我想得到它们的价值。
but this code of mine doesn't seem to be working
但我的这段代码似乎不起作用
$('#view-tags').click(function(){
$('li[data-value]').each(function(){
alert($(this).data("value"));
})
});
The whole code on jsfiddle: http://jsfiddle.net/Zn3JA/
jsfiddle 上的完整代码:http: //jsfiddle.net/Zn3JA/
回答by Christofer Eliasson
You are pretty close. You can use jQuery's .data()
method to read attributes that start with data-
. So in your case .data("value")
since your attribute is data-value="some"
.
你很接近。您可以使用 jQuery 的.data()
方法来读取以data-
. 所以在你的情况下,.data("value")
因为你的属性是data-value="some"
.
This should do it:
这应该这样做:
$('li[data-value]').each(function(){
alert($(this).data("value"));
});
Here is a working fiddle as well:http://jsfiddle.net/nuphP/
这也是一个工作小提琴:http : //jsfiddle.net/nuphP/
回答by Robin Drexler
$(this).attr('data-value')
should also work.
也应该工作。
回答by S P
You can use in your case:
您可以在您的情况下使用:
jQuery(this).data("value");
in order to retrieve the value.
以检索该值。
回答by Clyde Lobo
$(this)
refers to the current li
element hence you get the element alerted.
$(this)
指的是当前li
元素,因此您会收到该元素的警报。
You can try what the others have suggested i.e $(this).data("value")
你可以试试其他人的建议,即 $(this).data("value")
回答by Adriano Ernesto
$('#view-tags').click(function(){
$('li[data-value]').each(function(){
var value = $(this).attr('data-value');
alert(value);
})
}); // this work normally
Takes the attribute value and stores the variable value
获取属性值并存储变量值
var value = $ (this) .attr ('date value');
After this warning the variable value
在此警告之后变量值
alert (value);