jQuery $(document).on() 和 $(element).on() 有什么不同
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41820906/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is different between $(document).on() and $(element).on()
提问by plonknimbuzz
I know about jquery .on() use and purpose, because I use it.
我知道 jquery .on() 的使用和目的,因为我使用它。
But I want to know what is the difference between $(document).on()
vs $(element).on()
in this script:
但我想知道这个脚本中的$(document).on()
vs 有什么区别$(element).on()
:
<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?
他们之间有什么表现不同或其他什么吗?
采纳答案by Yeasir Arafat Majumder
Main difference is already answered by @Mukesh. I will try to add one more thing.
@Mukesh 已经回答了主要区别。我将尝试再添加一件事。
When you click(or any other event) on an element(like divor button) in the html document, that clicking event is propagated to the parent elements of that element. So if you have structure like this:
当您在 html 文档中的元素(如div或button)上单击(或任何其他事件)时,该单击事件将传播到该元素的父元素。所以如果你有这样的结构:
<div>
<table>
<tr>
<td>
<button>Click Me</button>
</td>
</tr>
</table>
</dvi>
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.
然后单击按钮,该单击将传播到 td,然后传播到 tr,然后传播到表格,最后传播到文档本身。
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.
现在假设您已经在文档($document.on('click',...))和按钮($(button.on('click',...)))上注册了一个点击事件,两者都执行一些不同的操作。然后点击按钮,就会执行相应的按钮动作,同时也会执行$(document)对应的动作。
To prevent the button click to propagate to the document itself, you need to take actions on the button click handler(like stopPropagation etc.)
为了防止按钮点击传播到文档本身,您需要对按钮点击处理程序采取行动(如 stopPropagation 等)
回答by Mukesh Ram
$(document).on('click','.btn-edit',function()
This binds a click event to the document and all child elements within it. This method is referred to as delegated event handling.
这会将单击事件绑定到文档及其中的所有子元素。此方法称为委托事件处理。
$('#table-user').on('click','.btn-edit',function()
binds the click event to the #table-user directly. captures the event directly on the element.
将点击事件直接绑定到#table-user。直接在元素上捕获事件。