如何使用包含在变量中的类项来计算元素
到目前为止http://jsfiddle.net/jGj4B/
var post = '<div/><div class="item"></div><div class="item"></div><div class="item"></div><div class="item"></div>';
alert($(post).find('.item').length); // i have tried .size() in place of .length
如何使用包含在变量中的类项来计算元素
到目前为止http://jsfiddle.net/jGj4B/
var post = '<div/><div class="item"></div><div class="item"></div><div class="item"></div><div class="item"></div>';
alert($(post).find('.item').length); // i have tried .size() in place of .length
你想要filter而不是find:
$(post).filter('.item').length
find寻找后代元素,但没有。
如果你想要顶级项目和后代,你可以这样做:
$(post).find('.item').andSelf().filter(".item").length
尽管按照另一个答案中的建议将其包装在一个跨度中可能更容易理解。
编辑 2013 年 7 月 19 日: andSelf自 v1.8 起已弃用,addBack应取而代之。
$(post).find('.item').addBack().filter(".item").length
最好的方法是创建一个 DOM 对象而不实际将其附加到 DOM。就像是:
var post = '<div/><div class="item"></div><div class="item"></div><div class="item"></div><div class="item"></div>';
// Create a dummy element:
var temp = $("<span />");
// Populate the HTML of that element with the data from your post variable
$(temp).html(post);
// Search the element as you normally would (if it were attached to the DOM)
$(temp).find(".item").length; // equals 4