javascript - jQuery 选择器上下文与最外层元素不匹配

标签 javascript jquery

在下面的代码片段中,为什么长度应该为 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/

相关文章:

javascript - 需要清楚地了解展平对象

javascript - 将 javascript 日期转换为 json 日期格式

javascript - != "undefined"上的 If 语句条件检查失败

javascript - 检查多个 div 以查看是否存在 h3

jquery - 如何自定义主题 jquery UI 选项卡(不使用 themeroller)

javascript - 滚动量后更改 CSS

javascript - 是否可以使用 javascript 测试用户的浏览器/操作系统是否支持给定类型的链接?

javascript - 如何从 SVGSVGElement 创建 SVGPathElement

javascript - 如何替换文本框中的逗号?

javascript - Jquery、CSS、SetTimeOut、GravityForms