简体   繁体   English

使用 function 参数添加事件监听器的 querySelector

[英]querySelector to addEventListener with function parameter

I try to pass a variable sel1 as parameter of function fxIn .我尝试将变量sel1作为 function fxIn的参数传递。
But event is not trigger, since this get no error in console, I don`t know what is going on.但是事件没有触发,因为这在控制台中没有错误,我不知道发生了什么。

var sel1 = window.document.querySelector('#item1')
sel1.addEventListener('mouseover', fxIn(sel1))
sel1.addEventListener('mouseout', fxOut(sel1))

the functions are:功能是:

// change bg color
function fxIn(selectorX){
    selectorX.style.background = 'red'
}

// reset bg color
function fxOut(){
    selectorX.style.background = ''
}

Why this don`t work?为什么这不起作用? the output expect is to have background color changed when mouse is over a div tag. output 期望在鼠标悬停在 div 标签上时更改背景颜色。

You can call the function inside of an anonymous function.您可以在匿名 function 内部调用 function。

sel1.addEventListener('mouseover', function(){ fxIn(sel1) })

Though you do not need to pass the same object on which you are attaching the event.尽管您不需要传递要附加事件的相同 object。 You can simply use this to refer the object directly:您可以简单地使用this来直接引用 object:

 var sel1 = window.document.querySelector('#item1') sel1.addEventListener('mouseover', fxIn); sel1.addEventListener('mouseout', fxOut); // change bg color function fxIn(){ this.style.background = 'red' } // reset bg color function fxOut(){ this.style.background = '' }
 #item1{ width: 200px; height: 200px; }
 <div id="item1">Container</div>

The second argument of addEventListener is expected to be a function, which can then be called by JS when the event occurs. addEventListener的第二个参数预计是 function,然后可以在事件发生时由 JS 调用。 You're calling your function (which returns undefined ), so, you're actually passing undefined as the second argument.您正在调用您的 function (返回undefined ),因此,您实际上将undefined作为第二个参数传递。

One possible solution would be to make your fxIn and fxOut return a function so that you can use it in the context of addEventListener like so:一种可能的解决方案是让您的fxInfxOut返回 function 以便您可以在addEventListener的上下文中使用它,如下所示:

 const fxIn = selectorX => e => selectorX.style.background = 'red'; const fxOut = selectorX => e => selectorX.style.background = ''; const sel1 = window.document.querySelector('#item1') sel1.addEventListener('mouseover', fxIn(sel1)); sel1.addEventListener('mouseout', fxOut(sel1));
 <p id="item1">Item 1</p>

Since the other others have the key points covered, here's an alternative solution that uses classList to toggle classes to the element.由于其他人已经涵盖了关键点,因此这里有一个替代解决方案,它使用classList将类切换到元素。

 const sel1 = document.querySelector('#item1'); function toggle() { this.classList.toggle('red'); } sel1.addEventListener('mouseover', toggle); sel1.addEventListener('mouseout', toggle);
 #item1 { width: 200px; height: 200px; }.red { background-color: red; }
 <div id="item1">Container</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM