开发者

jQuery data gives me undefined

开发者 https://www.devze.com 2023-02-15 07:06 出处:网络
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:

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.net/w95mY/1/

I expect to get "sida" from the al开发者_运维问答ert. I found out that it works if I delete the first list. Why is that? How do I solve it?


Consider 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".

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号