jQuery foo.html("bar") 没有改变 foo[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
吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
html()
写入/读取元素的innerHtml 属性;它不会替换该元素。您现在实际拥有的是
。所以不,这并不是特别奇怪的行为。 :)
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. :)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 thatdiv
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.