在Javascript中获取数据属性时出错

时间:2015-11-06 08:11:01

标签: javascript custom-data-attribute

我有一个节点,我分配了一个数据属性data-myid = "id3"。当我尝试打印此属性的值时,我不会id3而是nullundefined

这是代码:

console.log("node2");
console.log(node2);
console.log("node2.getAttribute(\"data-myid\") = " + node2.getAttribute("data-myid"));
console.log("node2.getAttribute(\"myid\") = " + node2.getAttribute("myid"));
console.log("node2.dataset.myid = " + node2.dataset.myid);

我尝试了不同的方法,但我得到的照片是:

enter image description here

为什么呢?如何获得myid的值? 非常感谢!

PS:为什么使用data attribute代替id取决于我的申请。因此,我不会使用myid更改id

此外,我使用 JavaScript ,而不是jQuery。

的jsfiddle : 我从未使用过JSFiddle,我不知道它是如何工作的。我这样做https://jsfiddle.net/xy1jxeos/但不完全是我的代码,这里简化了

好的有问题。我创建了这个简单的文件,看看问题是否在其他地方:

<!DOCTYPE html>
<html>
<head>
    <title>get attribute</title>
</head>
<body>

    <div id="main" data-myid="id3"></div>

    <script>
        console.log(document.getElementById("main"));
        console.log(document.getElementById("main").getAttribute("myid"));
    </script>

</body>
</html>

问题仍然存在!这是印刷品:

<div id="main" data-myid="id3"></div>
null

怎么可能?我哪里错了?

1 个答案:

答案 0 :(得分:-1)

您的node2似乎有问题 请提供您的分配方式。请检查此代码jsfiddle

var node2 = document.getElementById(element).children[0];

如果你喜欢这样,那就没关系。

相关问题