gpt4 book ai didi

Javascript 事件监听器在对象方法中不起作用

转载 作者:行者123 更新时间:2023-11-30 16:20:27 25 4
gpt4 key购买 nike

<分区>

考虑这段代码:

function Elements() {
this.mainSection = document.querySelector('.main-section');
this.searchBtn = document.getElementById('search');
this.searchBar = document.querySelector('.search-bar');
...
}

var initiate = new Elements();

initiate.toggleBar = function() {
console.log(this.mainSection);
}

initiate.addClick = function() {
this.searchBtn.addEventListener('click', this.toggleBar );
}

initiate.addClick();

在点击事件上它返回 undefined,带括号的它会自动运行函数。

为什么事件监听器会这样?

附言我只是在学习 Javascript,并尝试编写灵活的代码。这是我正在做的一个好习惯,还是我把事情复杂化了?

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