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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26956007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:44:51  来源:igfitidea点击:

jquery add data attribute while creating dynamic dom elements

javascriptjqueryhtmldom

提问by Ajey

How to add data attribute while creating custom dynamic dom elements

如何在创建自定义动态 dom 元素时添加数据属性

like -

喜欢 -

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);

Fiddle here - Demo

在这里小提琴 -演示

Here I have added data-childthis works, but when someone inspect elements via developer tools this is visible.

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

Where as the if I add via jquery .data() the data is not visible in the developer console.

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

But I am not able to figure out how to add data via jquery when I am creating elements on the fly.

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

采纳答案by Ashish

Updated the code and 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.

Working fiddle - http://jsfiddle.net/Ashish_developer/v0qmbL5z/1/

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

回答by Alexander T.

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/

演示:http: //jsbin.com/necoqo/1/