jquery在创建动态dom元素时添加数据属性

时间:2014-11-16 10:36:27

标签: javascript jquery html dom

如何在创建自定义动态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添加数据。

2 个答案:

答案 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'));

DEMO:http://jsbin.com/necoqo/1/

答案 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.

工作小提琴 - http://jsfiddle.net/Ashish_developer/v0qmbL5z/1/