admin管理员组文章数量:1391937
I'm trying the new data-function in jQuery but can't make it work.
Here is a little bit of code I use for testing:
HTML
<ul>
<li data-test="list">List item</li>
<li data-test="list">List item</li>
</ul>
<ul>
<li data-name="sida">oko</li>
</ul>
JS
var test = $('li').data('name');
alert(test);
The same thing on jsFiddle: /
I expect to get "sida" from the alert. I found out that it works if I delete the first list. Why is that? How do I solve it?
I'm trying the new data-function in jQuery but can't make it work.
Here is a little bit of code I use for testing:
HTML
<ul>
<li data-test="list">List item</li>
<li data-test="list">List item</li>
</ul>
<ul>
<li data-name="sida">oko</li>
</ul>
JS
var test = $('li').data('name');
alert(test);
The same thing on jsFiddle: http://jsfiddle/w95mY/1/
I expect to get "sida" from the alert. I found out that it works if I delete the first list. Why is that? How do I solve it?
Share Improve this question edited Dec 20, 2015 at 19:48 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Mar 6, 2011 at 14:58 Jens TörnellJens Törnell 24.8k46 gold badges130 silver badges223 bronze badges1 Answer
Reset to default 7Consider telling jQuery how to find exactly one element. For example, tell it to look for any li
element with a data-name
attribute:
var test = $('li[data-name]').data('name');
alert(test);
Or you can tell it to look for the last li
:
var test = $('li').last().data('name');
alert(test);
Both show an alert with text "sida".
本文标签: javascriptjQuery data gives me undefinedStack Overflow
版权声明:本文标题:javascript - jQuery data gives me undefined - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744680709a2619389.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论