javascript 如何使用getElementById获取ul标签中li标签的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30392283/
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 get value of li tag which is in ul tag using getElementById
提问by Vivek Gondliya
In this code I am getting in alert 0 insteadof 'abc'
在这段代码中,我进入了警报 0 而不是 'abc'
<ul>
<li>First Node</li>
<li id="repoFolder" value="abc">Lazy Node</li>
</ul>
<button onclick="rootFolder()">Click Me</button>
JS:
JS:
function rootFolder() {
alert(document.getElementById("repoFolder").value);
}
采纳答案by dfsq
You need to read attribute value, since HTMLLiElement
doesn't have value
property:
您需要读取属性值,因为HTMLLiElement
没有value
属性:
document.getElementById("repoFolder").getAttribute("value");
And since value
attribute is not defined in the specification for li
tag, it's better to use data-attribute (with .getAttribute("data-value")
):
并且由于标签value
规范中没有定义属性li
,所以最好使用数据属性(带.getAttribute("data-value")
):
<li id="repoFolder" data-value="abc">Lazy Node</li>
Then HTML will be valid and IDE's won't complain about unknown attributes.
然后 HTML 将有效并且 IDE 不会抱怨未知属性。
Check the demo below.
检查下面的演示。
function rootFolder() {
alert(document.getElementById("repoFolder").getAttribute('data-value'));
}
<ul>
<li>First Node</li>
<li id="repoFolder" data-value="abc">Lazy Node</li>
</ul>
<button onclick="rootFolder()">Click Me</button>
回答by dfsq
Try using getAttribute()
:
尝试使用getAttribute()
:
function rootFolder() {
alert(document.getElementById("repoFolder").getAttribute('value'));
}
<ul>
<li>First Node</li>
<li id="repoFolder" value="abc">Lazy Node</li>
</ul>
<button onclick="rootFolder()">Click Me</button>
回答by sonam gupta
You only have to replace the line
alert(document.getElementById("repoFolder").value); with
alert(document.getElementById("repoFolder").getAttribute('value'));
你只需要更换线
警报(document.getElementById(“repoFolder”)。值);和
alert(document.getElementById("repoFolder").getAttribute('value'));
回答by Vivek
Add the following line:
添加以下行:
alert(document.getElementById("repoFolder").getAttribute('value'));