2

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?

4

3 に答える 3

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

于 2011-10-20T22:48:28.720 に答える
1

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

于 2011-10-20T22:49:57.620 に答える
1

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

于 2011-10-20T22:51:19.633 に答える