jQuery在创建动态DOM元素时添加数据属性
jquery add data attribute while creating dynamic dom elements
如何在创建自定义动态 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);
在这里小提琴 - 演示
在这里,我添加了data-child
这有效,但是当有人通过开发人员工具检查元素时,这是可见的。
如果我通过 jquery .data() 添加数据,则数据在开发人员控制台中不可见。
但是当我动态创建元素时,我无法弄清楚如何通过 jquery 添加数据。
更新了代码和小提琴。
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.
工作小提琴 - http://jsfiddle.net/Ashish_developer/v0qmbL5z/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 );
或
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'));
演示:http://jsbin.com/necoqo/1/
相关文章:
- 无法将 json 数据添加到 pyjade 中的数据属性
- 添加数据属性及其值以使用纯javascript进行链接
- JavaScript / jquery:如果选择了单选按钮并且数据属性符合条件,则添加类
- 向ChartJS数据集添加其他属性
- 为selectize.js选项添加数据属性
- 动态添加数据时按数据属性查询JQuery选择器
- 数据属性在动态添加时不以所需的格式呈现,不转义双引号
- 将数据属性添加到标记并使用 JQuery 检索它
- 使用 jQuery 添加数据属性
- 映射 Json 数据并添加数据属性
- 是否可以向现有 JSON 数据添加新属性
- 和服:修改数据、分解字符串和添加新属性的功能
- 通过添加一些数据属性来防止特定 dom 的引导
- Vanilla JavaScript - 用于将类添加到具有特定数据属性的元素的语法
- jQuery在创建动态DOM元素时添加数据属性
- 添加具有self值的数据属性
- 如何将变量添加到附加的html数据属性中
- 正在尝试将数据属性值添加到其他页面上的输入中
- 添加数据属性值不工作
- 将json从php发送到autocomplete,并在输入中添加数据属性