这是我的JS代码:
var btn = document.querySelector("button");
btn.addEventListener("click", hide(this, true));
function hide(event, reflow) {
if(reflow) {
document.querySelector(".great").classList.add("hidden");
}
}有人能解释一下为什么会发生这种事吗?
发布于 2016-05-21 16:45:14
@blex解释函数为什么会立即执行是正确的,但是您所拥有的签名似乎正在尝试使用Function.prototype.call。以下是我的建议:
btn.addEventListener('click', function(event){ hide.call(this, event, true); });这样做是将匿名函数( function(event){...})的上下文传递给hide(),并将前两个参数e和reflow设置为event和true。
有关MouseEvent对象包含的属性类型,请参见event。
发布于 2016-05-21 16:34:07
在addEventListener行上,您将立即执行hide函数(使用括号)。您可以通过用匿名函数包装它来避免这种情况:
btn.addEventListener('click', function(){ hide(this, true); });正如@Patrick在下面所说的,它可能会对this所代表的东西产生影响。我不确定,所以我会让他或者其他人来解释。
发布于 2016-05-21 16:33:12
看这里。
btn.addEventListener('click', hide(this, true));您正在显式地调用hide(this, true)方法。方法addEventListener期望第二个参数中的函数引用在单击is get按钮时调用。所以你可以
btn.addEventListener('click', function(){ hide(this, true));https://stackoverflow.com/questions/37365468
复制相似问题