gpt4 book ai didi

javascript - addEventListener() 适用于作为参数传递的变量,但不能直接作用于变量?

转载 作者:行者123 更新时间:2023-12-03 01:25:25 24 4
gpt4 key购买 nike

我正在尝试在单击复选框(变量是“box”)时创建一个事件监听器。

为什么 box.addEventListener 会给出“不是函数”的错误,而当我调用以“box”作为参数的函数时却可以正常工作?

  <div class="inbox">
<div class="item">
<input type="checkbox">
<p>Item one</p>
</div>
<div class="item">
<input type="checkbox">
<p>Item two</p>
</div>
<div class="item">
<input type="checkbox">
<p>Item three</p>
</div>

<script>

有效的代码:

    const box = document.querySelectorAll('input');

function clickMe(param) {
this.addEventListener('click', function () {
return console.log('hi');
});
};

clickMe(box);

无效的代码:

const box = document.querySelectorAll('input');

box.addEventListener('click', function(){
return console.log('hi');
})

</script>

最佳答案

querySelectorAll() 返回匹配元素的列表。您需要迭代它们并为每个附加一个监听器

关于javascript - addEventListener() 适用于作为参数传递的变量,但不能直接作用于变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51573094/

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