jQuery在创建动态DOM元素时添加数据属性

jquery add data attribute while creating dynamic dom elements

本文关键字:添加 数据属性 元素 DOM 创建 动态 jQuery      更新时间:2023-09-26

如何在创建自定义动态 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/