我发现通过$()创建的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
Run Code Online (Sandbox Code Playgroud)
这是一个演示:http: //jsfiddle.net/5dVc8/
UPDATE
事实证明,我原来的问题太简单了.
@RocketHazmat的回答确实解决了我最初的问题,但当我去使用那些信息时,我发现我不够具体.
事实证明,我需要匹配根和/或孩子们的元素.似乎,正如@RocketHazmat所说,.find()匹配子,但.filter()只匹配根.
这里是更新的片段和演示的新小提琴:
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);
Run Code Online (Sandbox Code Playgroud)
和更新的小提琴:http://jsfiddle.net/XyDSg/2/
var found1 = dom.filter('[data-test]');
Run Code Online (Sandbox Code Playgroud)
.find()搜索所有孩子.在你的情况下,'[data-test]'是"根"元素,所以你需要.filter().
更新:
您可以将HTML包装在另一个中<div>,然后根据.find()需要工作.
var dom = $('<div>'+html+'</div>');
var found1 = dom.find('[data-test]');
Run Code Online (Sandbox Code Playgroud)
只要记得在将其附加到其他地方时将其删除.
$('#content').html(dom.html()); // This "removes" the parent `<div>`
Run Code Online (Sandbox Code Playgroud)