addEventListener to an element, with the element itself as parameter

一曲冷凌霜 提交于 2019-12-19 10:19:23

问题


First of all, sorry if the title isn't the best one, I couldn't find a better one.

How can I set a function as clickEvent for a Div using javascript, and at the same time also set the parameter of the function, to be the Div itself?
For example:

I have a HTML file that has:

<span id='parent'>
    <div class='child'></div>
</span>

And a JS file where I have the following code:

var el = document.getElementById("parent").getElementsByClassName("child")[0];
el.onclick = someFuntion(this);

But the thing is, I want that the this paramenter refer to the div.child, so that when I click the Div it should pass itself as a parameter, as a DOM element, making me able to use it inside of someFuntion(element) just like any other DOM element: element#id, for example.

Solutions tried:

el.addEventListener("click", someFuntion(event), false);
el.addEventListener("click", someFuntion(this), false);
el.addEventListener("click", someFuntion(el), false);
$("#parent #child").bind("click", someFuntion(this));
el.onclick = someFuntion(divIntoSpan);

SOLUTION:
el.onclick = someFuntion;

function someFunction(e){
    if(e.target){
        //remember to use "e.target" from here on, instead of only "e"
        //e.id (error: undefined); e.target.id (correct)
    }
}

回答1:


Solution

Just do el.addEventListener("click", someFunction); <- not someFunction()

and then use event.target

function someFunction(e) {
   if(e.target) ...
}

Alternative solution

If you like @JaromandaX's solution, you could simplify it to

el.addEventListener("click",someFunction.bind(null,el));

Note that bind returns function. This example should clarify it:

function someFunction(el) {
  // if used with bind below, the results are:
  console.log(this); // "This is it!"
  console.log(el); // the clicked element
}

a.addEventListener("click",someFunction.bind("This is it!",a));

Advice

  • someFunction is the function itself
  • someFunction() is what the function returns

If you want to be a good coder, you shouldn't be satisfied with It works!. It is worthy to spend some time to find out why it works. Without this step you can't be sure if your code doesn't contain hidden bugs in some cases.

What you have in Solutions tried is Programming by permutation which is an antipattern - I highly recommend reading this great wiki article about antipatterns.




回答2:


if, for some reason you must do it the way you want

el.addEventListener('click', function(e) { 
    someFunction(e.target);
}, false);

but the answer given by Jan Turoň is the preferred way



来源:https://stackoverflow.com/questions/31272118/addeventlistener-to-an-element-with-the-element-itself-as-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!