在下面的代码片段中,为什么长度应该为 1 而为 0?
var jQueryObj = $("<p>testing</p>");
// Display the length
$('body').html($("p", jQueryObj).length);
<script src="http://code.jquery.com/jquery-2.2.0.js"></script>
最佳答案
当您提供上下文时,您是在告诉 jQuery 在该上下文中查找 p
元素,因此您的选择器将查找任何 p
的子标签上下文。
如果您将容器添加到上下文中,它将能够找到该元素。
var jQueryObj = $("<div><p>testing</p></div>");
// Display the length
$('body').html($("p", jQueryObj).length);
<script src="http://code.jquery.com/jquery-2.2.0.js"></script>
关于javascript - jQuery 选择器上下文与最外层元素不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9031031/