bar") 没有改变 foo[0],那么这是什么意思呢?" />

jQuery foo.html("bar") 没有改变 foo[0],那么这是什么意思呢?

发布于 2024-09-11 12:35:12 字数 531 浏览 3 评论 0 原文

使用jQuery,在Firebug中,如果一一进行如下操作:

foo = $('<div>foo</div>')

foo[0]  // => <div>

foo.html('<span>bar</span>')

foo.html()  // => "<span>bar</span>"

foo[0]  // => <div>

$('body').prepend(foo)  // => shows bar at top of page

奇怪的是foo.html()显示的是span,但是foo[0] 显示 div...为什么不一致?看起来 foo 成为了 span 元素的 jQuery 包装器。 foo[0] 不应该也显示 span 吗?

Using jQuery, in Firebug, if the following is done one by one:

foo = $('<div>foo</div>')

foo[0]  // => <div>

foo.html('<span>bar</span>')

foo.html()  // => "<span>bar</span>"

foo[0]  // => <div>

$('body').prepend(foo)  // => shows bar at top of page

it is strange that foo.html() shows the span, but foo[0] shows the div... why is the inconsistency? It seems that foo became a jQuery wrapper for a span element. Shouldn't foo[0] show the span also?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

记忆之渊 2024-09-18 12:35:12

html() 写入/读取

元素的innerHtml 属性;它不会替换该元素。您现在实际拥有的是

bar

。所以不,这并不是特别奇怪的行为。 :)

html() writes/reads the innerHtml property of the <div> element; it doesn't replace the element. What you actually have now is <div><span>bar</span></div>. So no, this isn't particularly strange behavior. :)

昨迟人 2024-09-18 12:35:12

jQuery 对象上的索引访问器访问 jQuery 序列中的元素。在您的示例中,您创建了一个仅包含一个元素 - div 的 jQuery 序列。您可以将该 div 的内容设置为任何类型的复杂树,但它仍然只是一个元素。 html('') 设置节点的内部内容,但外部节点保持不变。

The index accessor on a jQuery object accesses the element in the jQuery sequence. In your example, you've created a jQuery sequence with just one element - the div. You can set the contents of that div to be any kind of complex tree, but it's still just one element. html('') sets the inner contents of the node, but the outer node remains unchanged.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文