我想要一个包含 <ul>
中的值的数组(或者简单的字符串值,如果不是数组的话) .我的代码如下:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h2>Unordered List with Disc Bullets</h2>
<ul style="list-style-type:disc">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
<button onclick="changeColor()">Change</button>
<script type="text/javascript">
function changeColor(){
var a=document.childNodes[1].childNodes[2].childNodes[3];
alert(a.childNodes[0]);
}
</script>
</body>
</html>
我收到警报的值是未定义的或 [object text],而我想要一个数组,以便我可以使用 array[0] 或类似的东西访问它们。
最佳答案
function changeColor() {
var a = document.querySelectorAll('ul li')
console.log(a[0].innerHTML);
}
<h2>Unordered List with Disc Bullets</h2>
<ul style="list-style-type:disc">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
<button onclick="changeColor()">Change</button>
对于使用 li text 创建 Nodelist 数组 和 forEach()
迭代数组。然后将 textContent 推送到数组 arr
function changeColor() {
var arr=[];
document.querySelectorAll('ul li').forEach(function(a){
arr.push(a.textContent)
})
console.log(arr);
}
<h2>Unordered List with Disc Bullets</h2>
<ul style="list-style-type:disc">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
<button onclick="changeColor()">Change</button>
关于javascript - 如何在 javascript 中使用 DOM 访问列表值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44951501/