gpt4 book ai didi

javascript - forEach 回调不使用 getElementsByClassName 执行

转载 作者:太空狗 更新时间:2023-10-29 15:29:50 25 4
gpt4 key购买 nike

在下面的代码中,

<!DOCTYPE html>
<html>
<head>
<title>Hide odd rows</title>
<meta charset="UTF-8">
</head>
<body>
<div style="background-color:#8F9779;width:200px;height:30px;">
</div>
<hr style="width:200px" align="left">
<table border="1" >
<tr class="hide" >
<td width="40" height="20">row 1</td>
</tr>
<tr>
<td width="40" height="20">row 2</td>
</tr>
<tr class="hide">
<td width="40" height="20">row 3</td>
</tr>
<tr>
<td width="40" height="20">row 4</td>
</tr>
<tr class="hide">
<td width="40" height="20">row 5</td>
</tr>
</table><br>
<button type="button" name="HideRows">Hide Odd Rows</button>
<script type="text/javascript" src="hideOddRows.js"></script>
</body>
</html>

/* hideOddRows.js */
document.querySelector('[name=HideRows]').onclick = hideRows;

function hideRows(){
var elements = document.getElementsByClassName('hide');
elements.forEach(function(element){
element.style.visibility = "hidden";
});
return true;
}

根据调试,elements 数组的每个 element 的回调函数不会在点击事件时执行。

我将 elements 视为键控集合,如下所示。

enter image description here

--

如何解决这个错误?

最佳答案

forEach 未包含在 getElementsByClassName 返回的类数组 HTMLCollection 对象的原型(prototype)中。

HTMLCollection 实例类似于数组,因为您可以通过索引访问元素,但它不包括数组的所有方法,正如您在 forEach< 中发现的那样.

但是,您可以通过访问 Array 原型(prototype)中的方法来手动调用对象上的方法。

var elements = document.getElementsByClassName('hide');
Array.prototype.forEach.call(elements, function(element){
element.style.visibility = "hidden";
});

关于javascript - forEach 回调不使用 getElementsByClassName 执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34303786/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com