Jquery.find返回的对象通过.data()行为意外(Object returned by Jquery.find behaving unexpectedly with .data())

编程入门 行业动态 更新时间:2024-10-15 14:13:31
Jquery.find返回的对象通过.data()行为意外(Object returned by Jquery.find behaving unexpectedly with .data())

看看这个例子:

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> 
  
 

更多推荐

本文发布于:2023-08-04 00:23:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1405303.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   意外   data   Jquery   find

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!