如何在创建自定义动态dom元素时添加数据属性
喜欢 -
var div = $('#ajey');
var text = "<div class='parent'>parent div";
text +="<div class='child' data-child='true'>how do I add .data value for this div during on the fly dom creation?</div>";
text += "</div>";
div.html(text);
小提琴 - Demo
我在这里添加了data-child
,但当有人通过开发人员工具检查元素时,这是可见的。
如果我通过jquery .data()添加,那么数据在开发者控制台中是不可见的。
但是当我在运行中创建元素时,我无法弄清楚如何通过jquery添加数据。
答案 0 :(得分:1)
var div = $('#ajey');
var text = "<div class='parent'>parent div";
text +="<div class='child' data-child='true'>how do I add .data value for this div during on the fly dom creation?</div>";
text += "</div>";
var parent = $(text);
parent.attr("data-foo", "bar");
parent.find('.child').attr("data-foo", "bar");
div.html( parent );
OR
var parent = $(text);
parent.data("foo", "bar");
parent.find('.child').data("foo", "bar");
div.html( parent );
console.log($('.parent').data('foo'));
console.log($('.parent').find('.child').data('foo'));
答案 1 :(得分:0)
更新了代码和小提琴。
var div = $('#ajey');
var text = "<div class='parent'>parent div";
text +="<div class='child'>how do I add .data value for this div during on the fly dom creation?</div>";
text += "</div>";
div.html(text);
div.find('.child').data('child', 'true'); //data-child attribute is added but will not show in DOM when user inspects element
console.log($('.child').data('child')); //you can see the value of data-child attribute in console to make it confirm that it is added.