gpt4 book ai didi

jquery - jQuery 能否在元素附加到文档之前找到它们?

转载 作者:行者123 更新时间:2023-12-03 23:03:35 25 4
gpt4 key购买 nike

我发现通过 $() 创建的 HTML/DOM 在附加到文档之前是不可搜索的。这是预期的结果,还是我做错了什么?

var html = "<div data-test='test'>testdiv</div>";

// Convert HTML string to an orphaned JQ DOM object
var dom = $(html);

// Search orphaned DOM for element(s) with the specified attr
var found1 = dom.find('[data-test]');
// --> found1.length == 0, why not 1?

// Now insert the orphaned DOM into the document
$('#content').html(dom);

// And now JQ will find the desired elements
var found2 = $('[data-test]');
// --> found2.length is 1, as expected

这是一个演示: http://jsfiddle.net/5dVc8/

更新

事实证明我原来的问题太简单了。

@RocketHazmat 的回答确实解决了我最初提出的问题,但当我使用该信息时,我发现我不够具体。

事实证明,我需要匹配根中的元素和/或子元素。似乎,正如 @RocketHazmat 所说, .find() 匹配子项,但 .filter() 只匹配根。

这是更新的代码片段和演示的新 fiddle :

var html = "<div data-test='test1'>";     // Root
html += "<div data-test='test2'></div>"; // Child
html += "</div>";

// Convert HTML string to an orphaned JQ DOM object
var dom = $(html);

// Search orphaned DOM object for element(s) with the specified attr
// (We'll find none)
var found1 = dom.find('[data-test]');
$('#count1').html('count1='+found1.length+", val="+found1.attr('data-test'));

// Search orphaned DOM object for element(s) with the specified attr
// (We'll find none)
var found2 = dom.filter('[data-test]');
$('#count2').html('count2='+found2.length+", val="+found2.attr('data-test'));


// Now append the orphaned DOM to the document
$('#content').html(dom);

// And now JQ will find the desired elements
var found3 = $('[data-test]');
$('#count3').html('count3='+found3.length);

和更新的 fiddle :http://jsfiddle.net/XyDSg/2/

最佳答案

尝试使用 .filter() 而不是 .find() .

var found1 = dom.filter('[data-test]');

.find()搜索所有 child 。在你的情况下,'[data-test]'是“根”元素,所以你需要 .filter() .

更新:

您可以将 HTML 包装在另一个 <div> 中,然后.find()会按照你想要的方式工作。

var dom = $('<div>'+html+'</div>');
var found1 = dom.find('[data-test]');

当您将其附加到其他位置时,请记住将其删除。

$('#content').html(dom.html()); // This "removes" the parent `<div>`

关于jquery - jQuery 能否在元素附加到文档之前找到它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18594568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com