addEventListener('click')自行执行 [英] addEventListener('click') is executing on its own
问题描述
在我的JavaScript(ES6)中,我有一个带有事件处理程序的简单< a>
标记,基本上是单击了我想要的< a>
标记时要重定向的页面.
In my javascript (ES6), I have a simple <a>
tag with an event handler, basically when the <a>
tag is clicked I want the page to redirect.
我的问题是,当我将URL参数传递给处理重定向的函数时,无论是否单击了 addEventListener
,都会执行测试函数,因此,基本上,它只是向后重定向并单靠页面加载就可以了,这不是我想要的.
My problem is that when I pass the URL parameter to the function that handles the redirect, the test function executes regardless of whether the addEventListener
has been clicked or not, so it's basically just redirecting back and forth on its own on page load which is not what I want.
是否有任何原因 this.elem.addEventListener('click',this.test(this.elem.id),false);
单独执行?
Is there any reason this.elem.addEventListener('click', this.test(this.elem.id), false);
is executing on its own?
index.html:
index.html:
<a id="about" class="a-tag" target='_blank'>About</a>
about.html:
about.html:
<a id="index" class="a-tag" target='_blank'>Index</a>
Master.js:
Master.js:
import { Nav } from 'module/Nav';
(function() {
Nav.init();
})();
Nav.js:
export const Nav = {
elem: document.querySelector('.a-tag'),
init() {
this.render();
},
test(page) {
window.location.href = "/" + page + ".html";
},
render() {
if (this.elem) {
this.elem.addEventListener('click', this.test(this.elem.id), false);
}
}
};
推荐答案
因为您没有传递函数的引用,而是传递了函数的结果.您调用直接重定向的函数.替换为此
Because you don't pass the reference of the function, but the result of the function. You call function which redirects directly. Replace with this
this.elem.addEventListener('click', () => this.test(this.elem.id), false);
这篇关于addEventListener('click')自行执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!