admin管理员组

文章数量:1313121

I tried to use the method data (jQuery 1.7.1) in this code:

var q = '<div class="form-error-marker"></div>';
var t = $(q).data('message', message).insertAfter(el); 

and it does not work.

Note that this works:

var t = $(q).attr('data-message', message).insertAfter(el);

Why does the first variant not work?

EDIT: insertAfter works correctly and new div is added after el (which is instance of one element which I get by getElementById() function; long story short I have a library that I extend).

When I say 'it does not work' I mean that the attribute 'data-message' is not stored.

I tried to use the method data (jQuery 1.7.1) in this code:

var q = '<div class="form-error-marker"></div>';
var t = $(q).data('message', message).insertAfter(el); 

and it does not work.

Note that this works:

var t = $(q).attr('data-message', message).insertAfter(el);

Why does the first variant not work?

EDIT: insertAfter works correctly and new div is added after el (which is instance of one element which I get by getElementById() function; long story short I have a library that I extend).

When I say 'it does not work' I mean that the attribute 'data-message' is not stored.

Share Improve this question edited Dec 20, 2015 at 23:52 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Dec 25, 2011 at 19:30 MartyIXMartyIX 28.7k32 gold badges139 silver badges217 bronze badges 4
  • +1 I have the exact same issue. – Bojangles Commented Dec 25, 2011 at 19:33
  • 1 What does "doesn't work" mean? Does el contain more than one element? – SLaks Commented Dec 25, 2011 at 19:35
  • SLaks: see the question update, please. – MartyIX Commented Dec 25, 2011 at 19:37
  • It does work. jsfiddle/7payvwgg – Popnoodles Commented Nov 14, 2014 at 13:55
Add a ment  | 

2 Answers 2

Reset to default 7

Using data like that sets an arbitrary piece of data for this node; it doesn't add a new data- attribute. Just add the attribute with the attr function, and then access it with data

var q = $('<div class="form-error-marker"></div>').attr("data-message", message);

Now access it like this:

var message = q.data("message");

Here's a fiddle

When you use jQuery.data you don't change element attributes, instead your data saved in $.cache. So if you want to change element attributes use jQuery.attr, when you want to save some info use jQuery.data

本文标签: javascriptAdding custom data attribute for a new node in Jquery does not workStack Overflow