javascript 无需 jQuery 即可访问“数据-”属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15912246/
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
Access 'data-' attribute without jQuery
提问by user2143356
Can I access a data- attribute without jQuery?
我可以在没有 jQuery 的情况下访问数据属性吗?
It's easy with jQuery, but I can't see anywhere how to do it without jQuery.
使用 jQuery 很容易,但我无法在没有 jQuery 的情况下看到如何做到这一点。
If I search on Google 'without jQuery' all I get is jQuery examples.
如果我在 Google 上搜索“没有 jQuery”,我得到的只是 jQuery 示例。
Is it even possible?
甚至有可能吗?
回答by fredrik
On hereI found this example:
在这里我找到了这个例子:
<div id='strawberry-plant' data-fruit='12'></div>
<script>
// 'Getting' data-attributes using getAttribute
var plant = document.getElementById('strawberry-plant');
var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12'
// 'Setting' data-attributes using setAttribute
plant.setAttribute('data-fruit', '7'); // Pesky birds
</script>
So it would appear very doable.
所以这看起来非常可行。
回答by tomor
You could use the datasetattribute. As in:
您可以使用数据集属性。如:
element = document.getElementById("el");
alert(element.dataset.name); // element.dataset.name == data-name
回答by drquicksilver
It's just an attribute ... use getAttribute
as with any other attribute : https://developer.mozilla.org/en/docs/DOM/element.getAttribute
它只是一个属性......getAttribute
与任何其他属性一样使用:https: //developer.mozilla.org/en/docs/DOM/element.getAttribute
Or am I missing the point of your question.
或者我错过了你的问题的重点。
回答by asim-ishaq
I think you can try this:
我想你可以试试这个:
var ele = document.getElementById("myelement");
if (ele.hasOwnProperty("data")) {
alert(ele.data);
}
OR use
或使用
alert(ele['data-property']);