【问题标题】:jquery add data attribute while creating dynamic dom elementsjquery在创建动态dom元素时添加数据属性
【发布时间】:2014-11-16 10:36: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);

在这里提琴 - Demo

我在这里添加了data-child 这可行,但是当有人通过开发人员工具检查元素时,这是可见的。

如果我通过 jquery .data() 添加数据在开发人员控制台中不可见。

但是当我动态创建元素时,我无法弄清楚如何通过 jquery 添加数据。

【问题讨论】:

  • jquery 的.data 实际上并没有添加 DOM 数据属性,而是将属性保留在 JS 土地中。
  • 哦,我如何关联 dom 的数据属性以保留在 JS 土地中?当我生成 dom 元素时?
  • 老实说,我会远离数据属性——如果你正在生成它们,你可以将它们推送到对象数组中,并将与它们相关的数据保留在表示层之外。如果必须,可以使用.attr$("&lt;div ... /&gt;").attr("data-foo", "bar")

标签: javascript jquery html dom


【解决方案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/

【讨论】:

    【解决方案2】:

    更新了代码和小提琴。

    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/

    【讨论】:

    • 在这种情况下,您在元素位于 DOM 之后添加数据属性。这不是“即时”。
    猜你喜欢
    • 1970-01-01
    • 2015-11-01
    • 2018-01-21
    • 2019-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-21
    • 1970-01-01
    相关资源
    最近更新 更多