admin管理员组

文章数量:1302913

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?

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?

Share Improve this question edited Nov 17, 2015 at 21:40 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Oct 20, 2011 at 22:45 Mustapha GeorgeMustapha George 2,53710 gold badges49 silver badges87 bronze badges 3
  • When you say you cannot see it, how exactly are you looking for it? You should be looking for it via the jquery API – Allen Rice Commented Oct 20, 2011 at 22:48
  • in firebug, I expect to seeit – Mustapha George Commented Oct 20, 2011 at 22:50
  • Works fine for me in FF 7.0.1 -- jsfiddle/KEwhf -- note: I removed the .css('background-image'...) line so that I didn't have to create that variable. – maxedison Commented Oct 20, 2011 at 22:50
Add a ment  | 

3 Answers 3

Reset to default 8

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() 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')

Use

$('#menu-container').attr('data-new_link','new_link.html');

it will appear in firebug, and you can also use the expected jQuery behavior

$('#menu-container').data('new_link');

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..

本文标签: javascriptAdd some properties to a ltdivgt elementStack Overflow