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
2 Answers
Reset to default 7Using 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
版权声明:本文标题:javascript - Adding custom data attribute for a new node in Jquery does not work - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741946246a2406430.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论