jQuery的动态绑定。对()选择父母或子女? [英] jquery dynamic binding .on() select parents or children?
问题描述
例如,
$( "#dataTable tbody tr" ).on( "click", function() {
alert( $( this ).text() );
});
$( "#dataTable tbody" ).on( "click", "tr", function() {
alert( $( this ).text() );
});
。对()结合TR与click事件处理程序。
第一个选择儿童和注册直接点击事件处理程序。
第二个选择父TBODY,并选择孩子TR作为参数。
.on() binds "tr" with click event handler. The first one select children and register click event handler directly. The second one select parent "tbody", and select children "tr" as an argument.
他们是两个动态绑定?
他们有同样的效果呢?
什么是这两者之间的区别?
Are they both dynamic binding? Do they have the same effect? What is the difference between these two?
推荐答案
没有,只有第二个版本是动态绑定。
No, only the second version is dynamic binding.
它应该是简单易懂。当你有code,如:
It should be simple to understand. When you have code like:
$(selector).method(arguments);
jQuery的找到所有匹配选择
在一次执行code的元素,并调用法
他们在那个时候。如果您执行此code第一次加载页面时,它只会找到最初文档中选择器匹配的元素。如果 TR
元素的动态添加,第一个版本将无法找到他们,所以不会click事件绑定到他们。
jQuery finds all the elements that match the selector
at the time you execute the code, and calls the method
on them at that time. If you execute this code when the page is first loaded, it will only find the elements that match the selector in the initial document. If the tr
elements are added dynamically, the first version will not find them, so it will not bind the click event to them.
当您使用。对()
与选择作为第二个参数,例如
When you use .on()
with a selector as the second argument, e.g.
$(outerSelector).on(event, innerSelector, function...);
它的工作原理如下。它发现所有符合 outerSelector
的元素,并结合该事件对他们的处理程序;这些因素都当你调用存在。对()
。当事件发生时,处理程序检查是否匹配目标 innerSelector
,然后执行回调函数。这是怎么回事允许的情况下工作的动态添加元素。
it works as follows. It finds all the elements that match outerSelector
, and binds a handler for the event to them; these elements have to exist when you call .on()
. When the event occurs, the handler checks whether the target matches innerSelector
, and then it executes your callback function. This is how it allows the event to work on dynamically-added elements.
所以,一般的规则是, outerSelector
应该是指一个静态的元素在文档中,而 innerSelector
指动态元素。
So the general rule is that outerSelector
should refer to a static element in the document, while innerSelector
refers to the dynamic elements.
这篇关于jQuery的动态绑定。对()选择父母或子女?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!