gpt4 book ai didi

javascript - getElementsByClassName 不起作用

转载 作者:行者123 更新时间:2023-11-30 21:19:02 26 4
gpt4 key购买 nike

我有一个问题,为什么我不想工作一段时间很累。我刚开始学js。非常感谢您的帮助

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<img class="test" src="https://storage.googleapis.com/gweb-uniblog-publish-prod/static/blog/images/google-200x200.7714256da16f.png">
<img class="test" src="https://storage.googleapis.com/gweb-uniblog-publish-prod/static/blog/images/google-200x200.7714256da16f.png">

<script>
var test = document.getElementsByClassName("test");
test.onclick = function () {
alert("test");
};
</script>
</body>
</html>

最佳答案

您需要为每个元素添加事件监听器。因此您需要遍历元素,因为 document.getElementsByClassName() 返回一个元素数组。你可以这样做:

function trigger() {
alert("test");
}

var test = document.getElementsByClassName("test");

for (var i = 0, j = test.length; i < j; i++) {
test[i].addEventListener("click", trigger);
}
<!DOCTYPE html>
<html>

<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>

<body>
<img class="test" src="https://storage.googleapis.com/gweb-uniblog-publish-prod/static/blog/images/google-200x200.7714256da16f.png">
<img class="test" src="https://storage.googleapis.com/gweb-uniblog-publish-prod/static/blog/images/google-200x200.7714256da16f.png">

<script src="script.js"></script>
</body>

</html>

关于javascript - getElementsByClassName 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45368755/

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