简体   繁体   English

通过jquery添加的数据属性不可用于选择元素

[英]data attribute added trough jquery is not being available to select the element

I have the following html code. 我有以下HTML代码。

<ul>
    <li  data-details="li1">first</li>
    <li  >second</li>
</ul>

Notice that for the first element i have add data-details attribute with a value. 请注意,对于第一个元素,我添加了data-details属性和值。 For the 2nd li element i'm adding the same using jquery. 对于第二个li元素,我使用jquery添加相同的元素。 Here is my JavaScript code. 这是我的JavaScript代码。

$(document).ready(function()
                  {
                      $("ul li:nth-child(2)").data("details","li2");
                      console.log($("ul li:nth-child(2)").data()); //data can be verified using this
                      alert($("ul li[data-details=li1]").length); //resulting in alert 1
                      alert($("ul li[data-details=li2]").length); //resulting in alert 0
                  });

The data is added we can verify by checking the console. 我们可以通过检查控制台来验证数据。 However i'm not able to select the element based on value of data-details which is being added by jquery. 但是我无法根据jquery添加的data-details值来选择元素。 Why is it happening so ? 为什么会这样?

and Here is the jsfiddle link 这是jsfiddle链接

Setting items with .data() does not set attributes. 使用.data()设置项目不会设置属性。 If you set the attribute in the HTML or use something like .attr() , you can use the attribute selector. 如果在HTML中设置属性或使用类似.attr()属性 ,则可以使用属性选择器。 If you need to find elements that have their .data() set, you need to use .filter() : 如果需要查找设置了.data()元素,则需要使用.filter()

var el = $("selector").filter(function () {
    return typeof $(this).data("whatever") !== undefined;
});
console.log(el.length);

Note that this isn't the same behavior in the opposite way. 请注意,这与相反的方式不同。 When you set an attribute in the HTML or with .attr() , any data-* attribute will automatically be put into .data() by jQuery. 当您在HTML中设置属性或使用.attr() ,任何data-*属性都将由jQuery自动放入.data()

DEMO: http://jsfiddle.net/zTsS4/2/ 演示: http //jsfiddle.net/zTsS4/2/

Note how in the demo, the attribute is set in the HTML for one <li> , and the other is set with .data() . 请注意,在演示中,属性是在HTML中为一个<li>设置的,另一个是使用.data() Then the .filter() finds both. 然后.filter()找到两者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM