如何在处理程序有参数时获取事件单击对象

时间:2022-11-09 20:35:24

In the following example, if we add handler to addEventListener without any args, then Event click object is automatically passed as argument to the handler.

在下面的示例中,如果我们将addEventListener添加到没有任何args的处理程序,则Event click对象将自动作为参数传递给处理程序。

<table id="outside">
    <tr><td id="t1"> one </td></tr>
    <tr><td id="t2"> two </td></tr>
</table>

<script>
    function modifyText(e,text) 
    {
        console.log(e); // logs => click clientX=100, clientY=21
    }

    // add event listener to table
    var el = document.getElementById("outside");

        el.addEventListener("click", modifyText, false);                     //method 1
    //  el.addEventListener("click", function(){modifyText("four")}, false); //method 2
</script>   

But if you pass any args to the handler, then Event click object is not passed. How to get the Event click obj along with args in handler

但是如果将任何args传递给处理程序,则不会传递事件单击对象。如何获取事件单击obj以及处理程序中的args

1 个解决方案

#1


1  

If you use an anonymous function, event is auto passed in:

如果您使用匿名函数,则会自动传入事件:

el.addEventListener("click", function(event){
    //event is passed
    modifyText("four") //add another param here to pass 'event' along with your param
}, false);

If you specify a function as the callback, you get the default params, as above (event being the first one)

如果您指定一个函数作为回调,您将获得默认参数,如上所述(事件是第一个)

You'll have to pass it along to your function via a second parameter if you want more params.

如果你想要更多的参数,你必须通过第二个参数将它传递给你的函数。

#1


1  

If you use an anonymous function, event is auto passed in:

如果您使用匿名函数,则会自动传入事件:

el.addEventListener("click", function(event){
    //event is passed
    modifyText("four") //add another param here to pass 'event' along with your param
}, false);

If you specify a function as the callback, you get the default params, as above (event being the first one)

如果您指定一个函数作为回调,您将获得默认参数,如上所述(事件是第一个)

You'll have to pass it along to your function via a second parameter if you want more params.

如果你想要更多的参数,你必须通过第二个参数将它传递给你的函数。