为什么使用委托事件侦听器?
1)内容尚不存在
//#container is empty, but we will create children in the future
//we can use a delagate now that will handle the events from the children
//created later
$('#container').on('click', '.action', function (e) {
console.log(e.target.innerText);
});
//lets create a new action that didn't exist before the binding
$('#container').append('<button class="action">Hey! You Caught Me!</button>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container"></div>
2)内容存在,但有变化
//#container has an existing child, but it only matches one of our
//delegate event bindings. Lets see what happens when we change it
//so that it matches each in turn
$('#container').on('click', '.action:not(.active)', function (e) {
console.log('Awww, your not active');
$(e.target).addClass('active');
});
$('#container').on('click', '.action.active', function (e) {
console.log('Hell yeah! Active!');
$(e.target).removeClass('active');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<button class="action">Hey! You Caught Me!</button>
</div>
为什么在委托事件侦听器上使用非委托事件侦听器?
1)内容是静态的和预先存在的
要么是因为你知道内容是静态的,不会改变,你不需要一个。否则,您可能有使用委托的首选项,这与开发人员首选项一样好。
2)可以防止事件冒泡
但是,使用非委托事件侦听器也可以与委托一起使用,以防止操作。请考虑以下几点:
//#container has three children. Lets say we have a delegate listener for
//the buttons, but we only want it to work for two of them. How could we
//use a non-delegate to make this work?
//delegate that targets all the buttons in the container
$('#container').on('click', 'button', function (e) {
console.log('Yeah!');
});
$('.doNotDoSomething').on('click', function (e) {
console.log('Do not do the delegate logic');
//by stopping the propagation of the click event, it will not bubble up
//the DOM for the delegate event handler to process it. In this way, we
//can prevent a delegate event handler from working for a nested child.
e.stopPropagation();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<button class="doSomething">Do It!</button>
<button class="doNotDoSomething">Nooooo!</button>
<button class="doSomethingElse">Do This Instead!</button>
</div>
3)你希望你的绑定是可移动的
可能希望使用非委托事件侦听器的另一个原因是
是
依附于元素本身。因此,如果删除元素,绑定也会随之消失。虽然这可能是动态内容的一个问题,您希望元素的绑定始终存在,但在某些情况下,您可能希望这样做。