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

标签 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 添加数据。

最佳答案

更新了代码和 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/

相关文章:

javascript - trim jQuery .load 的结果

javascript - jQuery sortable 当排序元素的 id 按升序而不是排序顺序排序时

jquery - 如何解决 IE8 限制 live ('change' ) 不触发 AJAX 元素?

html - 选择图像的哪一部分显示在小于图像大小的容器中

javascript - 使用 jquery scrollify 更改固定 div 的 Div 内容

javascript - 使用 jquery waypoints 插件淡出元素

javascript 将 cookie 设置为 httponly

javascript - javascript中如何识别输入是否为小数

javascript - javascript中使用reduce和each压平函数

javascript - 如何设置 jQuery 可拖动最小/最大左和最小/最大右