javascript 如何设置 data-id 属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13054286/
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
How to set data-id attribute
提问by myTD
I am trying to set the data-id and/or value of a span from my js file after a click event.
我试图在单击事件后从我的 js 文件设置数据 ID 和/或跨度值。
<span id="test"></span>
my sudo code js file
我的 sudo 代码 js 文件
nextLink: function(event) {
$('#test').val = 3;
$('#test').data('id') = 'Next';
},
回答by Sushanth --
Try setting it as an attribute..
尝试将其设置为属性..
$('#test').attr('data-id' , 'Next'); // JQuery
You can also try the setAttribute()
..
你也可以试试setAttribute()
..
var d = document.getElementById("test"); // Javascript
d.setAttribute('data-id' , 'Next'); //
Using this approach will reflect the new attribute in the DOM
使用这种方法将反映 DOM 中的新属性
In your code You are trying to set the attribute which is not present .. So you need to add the attribute first to add that ..
在您的代码中,您正在尝试设置不存在的属性 .. 因此您需要先添加该属性以添加该 ..
回答by rinat.io
You probably need this:
你可能需要这个:
$('#test').data('id', 'Next');