将元素添加到元素的最佳方式 [英] The best way to add eventlistener to an element

查看:96
本文介绍了将元素添加到元素的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想我们有这样的结构:

 < ul> 
< li>第一li< / li>
...
< li> 99999th li< / li>
< ul>

所以,我们有大约10000个li元素,我们要为所有这些元素添加事件监听器说我们也可以使用jQuery。



第一个想法

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

此解决方案的一部分 - 我们增加了一个大小的html标记,因为总是重复onlick



第二个想法

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

当然,这个解决方案不是一个选择,因为我们添加了10000个事件监听器,显然不是很好的表现。



/ strong>,事件委托

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

看起来真的很好对于我来说,我们只使用一个事件监听器,而不是垃圾HTML标记,它的工作原理是我们需要的。



所以,我提出这个问题,因为有时候我看看源不同的网站,大部分人使用第一种方式。为什么?第一种方式有一些优点?



我猜这可能是因为它更容易捕捉动态添加的元素到页面,但可能有一些我不知道的东西?

解决方案

我不会看到最好的网页开发实践的大网站。第一种方式与其他两种方式相比,实际上没有任何优势,因为它将JavaScript与HTML混合起来,更难维护。



事件委托将比其他两个更轻,具有能够处理动态生成的元素的优点,因此在这种情况下,它可能是最好的选择。在选择之前,我将使用两种方法配置您的应用程序。


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 ?

解决方案

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.

这篇关于将元素添加到元素的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆