看看这个例子:
let ele = $(` <div></div> <div class="test" id="test" data-test="test"></div>` ); const ele1 = ele.find('.test'); //undefined const ele2 = ele.find('#test'); //undefined console.log(ele1.data()); console.log(ele2.data()); ele = $('<div class="test" id="test" data-test="test"></div>'); console.log(ele.data()); //works<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>.find()返回的对象和$()返回的对象之间似乎有区别。
我假设它与第一个ele是两个没有父母的兄弟姐妹有关,但考虑到这个不能改变 ,我怎么能得到#test的数据?
我无法找到任何地方当你创建一个没有像我这样的父母的元素时,预期的行为是什么,为什么会发生这种情况。
小提琴: https : //jsfiddle.net/xpvt214o/26285/
Take a look at this example :
let ele = $(` <div></div> <div class="test" id="test" data-test="test"></div>` ); const ele1 = ele.find('.test'); //undefined const ele2 = ele.find('#test'); //undefined console.log(ele1.data()); console.log(ele2.data()); ele = $('<div class="test" id="test" data-test="test"></div>'); console.log(ele.data()); //works<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>There seems to be a difference between the object returned by .find() and the one returned by $()
I'm assuming it has something to do with the first ele being two siblings with no parent, but considering this can't be changed, how can I get #test's data?
I couldn't find anywhere what's the expected behaviour when you create an element with no parent like I did, and why does this happens.
Fiddle : https://jsfiddle.net/xpvt214o/26285/
最满意答案
您可以将该HTML包装在一个div中,以便能够在其上使用find() 。 但是,如果您无法更改HTML,则可以使用filter() ,因为它是jQuery元素的集合:
// Your element, as you defined it in your question let ele = $(` <div></div> <div class="test" id="test" data-test="test"></div>` ); console.log(ele.filter('.test').data());<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>You can just wrap that HTML inside a single div to be able to use find() on it. But, if you can't change the HTML, you can do it using filter(), since it's a collection of jQuery elements:
// Your element, as you defined it in your question let ele = $(` <div></div> <div class="test" id="test" data-test="test"></div>` ); console.log(ele.filter('.test').data());<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
更多推荐
发布评论