如何防止孩子影响父母

Dav*_*vid 6 jquery parent-child javascript-events

如何防止CHILD元素影响PARENT元素?

jQuery的:

$("#parent").click(function() {
    alert('parent clicked');
});
$("#child").click(function() {
    alert('child clicked');
});
Run Code Online (Sandbox Code Playgroud)

HTML:

<div id="parent">
    click me - parent
    <div id="child">click me - child</div>
</div>
Run Code Online (Sandbox Code Playgroud)

如果您单击该子项,则父项也会被激活,我们会有2个警报.

那么如何防止孩子影响父母呢?

Cra*_*aig 10

event.stopPropagation()

$("#child").click(function(event) {

    event.stopPropagation();

    alert('child clicked');
});
Run Code Online (Sandbox Code Playgroud)

调用event.stopPropagation()将阻止事件冒泡DOM树.