$(document).on()和$(element).on()之间有什么区别 [英] What is different between $(document).on() and $(element).on()

查看:221
本文介绍了$(document).on()和$(element).on()之间有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解jquery .on()的用途和目的,因为我使用了它.

I know about jquery .on() use and purpose, because I use it.

但是我想知道此脚本中$(document).on()$(element).on()之间的区别是什么

But I want to know what is the difference between $(document).on() vs $(element).on() in this script:

<html>
...
<body>
...
  <table id="table-user">
    <thead>...</thead>
    <tbody>
      AJAX DYNAMIC CONTENT
    </tbody>
  </table>
....
<script>
  $(document).on('click','.btn-edit',function(){
    go_edit();
  });

  $('#table-user').on('click','.btn-edit',function(){
    go_edit();
  });

</script>
</body>
</html>

在性能上有什么不同吗?

is any performance different or something else between them?

推荐答案

@Mukesh已经回答了主要区别. 我将尝试再添加一件事.

Main difference is already answered by @Mukesh. I will try to add one more thing.

当您在html文档中的元素(例如 div button )上单击(或其他任何事件)时,该单击事件将传播到的父元素该元素.因此,如果您具有这样的结构:

When you click(or any other event) on an element(like div or button) in the html document, that clicking event is propagated to the parent elements of that element. So if you have structure like this:

<div>
    <table>
        <tr>
            <td>
                <button>Click Me</button>
            </td>
        </tr>
    </table>
</dvi>

然后单击按钮,该单击将传播到td,然后传播到tr,然后传播到表,最后传播到文档本身.

and you click on the button, that click will propagate to the td, then to the tr, then to the table and then finally to the document itself.

现在,假设您已在文档( $ document.on('click',...))以及按钮( $(button. on('click',...))),两者都会执行一些不同的操作.然后,如果单击该按钮,则将执行相应的按钮动作,并且还将执行$(document)的相应动作.

Now lets say you have registered a click event on the document($document.on('click',...)) and also on the button($(button.on('click',...))), both of which does some different actions. Then if you click on the button, the corresponding button action will be executed, and also the corresponding action of the $(document) will also be executed.

为防止按钮单击传播到文档本身,您需要对按钮单击处理程序进行操作(例如stopPropagation等)

To prevent the button click to propagate to the document itself, you need to take actions on the button click handler(like stopPropagation etc.)

这篇关于$(document).on()和$(element).on()之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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