The best way to add eventlistener to an element

只谈情不闲聊 提交于 2019-12-10 19:31:46

问题


I'm trying to find the most productive way to hanging event.

Lets imagine we have this structure:

<ul>
    <li> 1st li </li>
    ...
    <li> 99999th li </li>
<ul>

So, we have about 10000 li elements and we want to add event listener to all this elements, lets say we can use jQuery too.

First thought

<li onclick="console.log(this)" >...</li>

bad part of this solution - we have increase a size of html markup because always repeating onlick.

Second thought

$('ul li').on('click', function(){ 
    console.log(this)
})

Of course this solution is not an option because we add 10000 event listeners, obviously not good for performance.

Third thought, event delegation

$('ul').on('click', 'li', function(){
    console.log(this)
})

looks really good as for me, we use only one event listener, not trashed html markup and it works as we need.

So, I asking this question, because sometimes I look at the source of different sites and big part of them use first way. Why? First way has some advantages?

I guess that maybe because it is easier to catch a dynamically added elements to the page, but may be there is something I do not know?


回答1:


I wouldn't look at "big sites" for the best web development practices. The first way has really no advantages over the other two, as it mixes JavaScript with HTML and is harder to maintain.

Event delegation will be lighter than the other two and will have the advantage of being able to handle dynamically generated elements, so in this case, it'd probably be the best choice. I would profile your application with both approaches before choosing.




回答2:


you can find your answer here- jQuery.click() vs onClick ,
As you can see http://jsperf.com/testper test, event delegation approach is the best approach for event hanging.In your case where you have 10000 or more events than surely 3rd approach is best for you.



来源:https://stackoverflow.com/questions/17255283/the-best-way-to-add-eventlistener-to-an-element

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