向添加一些属性元素
我想向
元素添加一些属性。除了 .data()
之外,以下所有内容均有效。我看不到它出现在 Firefox/Firebug 中。$('#menu-container')
.css('background-image','url("'+big_image+'")')
.addClass('click_2')
.data("new_link", "new_link.html")
.css('z-index',"99");
我做错了吗?
I want to add some properties to a <div>
element. All of the below works except for the .data()
. I cannot see it appear in Firefox/Firebug.
$('#menu-container')
.css('background-image','url("'+big_image+'")')
.addClass('click_2')
.data("new_link", "new_link.html")
.css('z-index',"99");
Am I doing it wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
data
不仅仅是可以添加的任何普通属性,它是一种将对象和数据附加到 DOM 元素的方法。您无法在 HTML 源或 Firebug 中看到它,但您可以使用.data()
查询它。数据本身并不存储在元素上。它实际上存储在 $.cache 中
data
is not just any ordinary attribute you can add, it is a way to attach objects and data to DOM elements. You can't see it in the HTML source or in Firebug, but you can query it using.data()
The data itself is not stored on the element. It's actually stored in $.cache
.data()
正在工作,但它不会显示为元素的属性。如果您想查看它的工作原理,可以尝试
console.log($('#menu-container').data('new-link'));
如果属性是您想要的,那么您可以执行
.attr('new-link','new-link.html')
.data()
is working but it won't show up as an element's attribute.If you wanted to see it working you can try
console.log($('#menu-container').data('new-link'));
If attributes are what you want then you can do
.attr('new-link','new-link.html')
使用
它会出现在firebug中,并且您还可以使用预期的jQuery行为
来检索存储的值。
但是确实没有必要这样做。无论是否作为属性添加到 DOM 元素,它都会存储在
.data()
集合中。Use
it will appear in firebug, and you can also use the expected jQuery behavior
to retrieve the value stored..
But there is really no need to do it this way. It gets stored at the
.data()
collection, regardless of being added as an attribute to the DOM element..