不使用 jQuery 访问“ data-”属性

没有 jQuery 我能访问数据属性吗?

使用 jQuery 很简单,但是如果没有 jQuery,我看不到任何地方可以做到这一点。

如果我在 Google 上搜索‘ without jQuery’,我得到的只是 jQuery 示例。

这有可能吗?

70571 次浏览

给你上,我发现了这样一个例子:

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

所以看起来非常可行。

更新: 由于微软现在(2020年)正在逐步淘汰旧的 Internet Explorer 引擎,转而使用基于 Chromium 的 Edge,因此 dataset的特性可能在任何地方都适用。在一段时间内,IE 仍然被迫使用的组织和公司网络将是一个例外。在写这篇文章的时候,JsPerf仍然显示 get/setAttribute 方法比使用数据集更快,至少在 Chrome 81上是这样。

它只是一个属性... ... 使用 getAttribute作为任何其他属性: https://developer.mozilla.org/en/docs/DOM/element.getAttribute

还是我没听懂你的问题。

您可以使用 数据集属性:

element = document.getElementById("el");
alert(element.dataset.name); // element.dataset.name == data-name

我想你可以试试这个:

var ele = document.getElementById("myelement");
if (ele.hasOwnProperty("data")) {
alert(ele.data);
}

或使用

alert(ele['data-property']);

你亦可使用:

getAttribute('data-property');

这样更干净,更容易阅读。

这将获得 data 属性的值。