2015-11-06 47 views
0

我有一个节点,我分配了一个数据属性data-myid = "id3"。当我尝试打印此属性的值时,我没有收到id3,但是收到了nullundefined在Javascript中获取数据属性时出错

这是代码:

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取决于我的应用程序。所以我不会改变myidid

另外我会只有使用JavaScript,而不是jQuery。

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


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

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

这怎么可能?我错在哪里?

+0

我以这种方式使用JavaScript添加属性:'node.childNodes [i] .dataset.myid = att.myID;'。使打印工作正常,属性被分配。 – lonely

+0

显示如何声明并分配'node2'。另外,你可以在SO片段或JSFiddle中重现这个问题吗? –

+0

哪个浏览器是这样的(看起来像chrome) –

回答

-1

看起来有什么不对node2 请提供你如何分配它。检查这个代码jsfiddle

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

如果你不喜欢这一点,那么它的确定。