如何在创建自定义动态 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 添加数据。
最佳答案
更新了代码和 fiddle 。
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.
工作 fiddle - http://jsfiddle.net/Ashish_developer/v0qmbL5z/1/
关于javascript - jquery在创建动态dom元素时添加数据属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26956007/