简体   繁体   中英

Why jQuery data won't work with append?

I am appending data from server to an unordered list, however setting data-id attribute with data() doesn't work, but attr() does.


When using data() :

Appends <li>Home</li>

 $('#menu').append($('<li>').text("Home").data('id', 5)); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul id="menu"> </ul> 

When using attr() :

Appends <li data-id="5">Home</li>

 $('#menu').append($('<li>').text("Home").attr('data-id', 5)); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul id="menu"> </ul> 

I know I could append it like so, but prefer the first option.

$('#menu').append('<li data-id="5">Home</li>');

The .data() method will read the data-* attribute as a secondary function. But what it first tries to do is read the data from jQuery's internal cache as a key-value pair (attached to the element).

The main takeaway is, it doesn't work the other way around. Ie .data() will not put attributes on an element. It will just store data in jQuery's internal cache to be associated with that element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM