gpt4 book ai didi

javascript - 如何获取具有相同类名的div内的子元素

转载 作者:行者123 更新时间:2023-11-28 17:35:19 26 4
gpt4 key购买 nike

我尝试从具有相同类的 div 子项创建一个触发按钮,但下面的代码似乎无法正常工作,我尝试首先进行循环以获取类框,然后尝试从每个框中获取子项,但似乎不起作用。

var container = document.querySelector(".container");

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

for(var i = 0; i < box.length; i++){
var x = box[i].children;
x.addEventListener("click", function(){
console.log('hello world')
})
}
.container {
border: 1px solid black;
padding: 10px;
}
.box {
width: 100px;
height: 100px;
background: red;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="container">
<div class="box">
<button class="btn">click me</button>
</div>
<div class="box">
<button class="btn">click me</button>
</div>
<div class="box">
<button class="btn">click me</button>
</div>
<div class="box">
<button class="btn">click me</button>
</div>
</div>
</body>
</html>

最佳答案

box[i].children 返回一个集合(请参阅 https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/children )

您需要循环它才能获取每个节点。

或者更好的是,使用 querySelector 访问所需的节点:

var container = document.querySelector(".container");

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

for(var i = 0; i < box.length; i++){
var button = box[i].querySelector('button');
button.addEventListener("click", function(){
console.log('hello world')
})
}
.container {
border: 1px solid black;
padding: 10px;
}
.box {
width: 100px;
height: 100px;
background: red;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="container">
<div class="box">
<button class="btn">click me</button>
</div>
<div class="box">
<button class="btn">click me</button>
</div>
<div class="box">
<button class="btn">click me</button>
</div>
<div class="box">
<button class="btn">click me</button>
</div>
</div>
</body>
</html>

关于javascript - 如何获取具有相同类名的div内的子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49274968/

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