即使事件处理程序也以父元素为目标,也只以子元素为目标

Only target child element even if event handler targets parent as well

本文关键字:目标 元素 事件处理 程序      更新时间:2023-09-26
<section id="first">
    <h1>Colors</h1>
    <section id="red">
        <h1>Red</h1>
        <section id="apples">
            <h1>Apples</h1>
        </section>
        <section id="apples">
            <h1>Strawberries</h1>
        </section>
    </section>
    <section id="orange">
        <h1>Orange</h1>
    </section>
</section>
$('section').click(function(){
    $(this).css('color','yellow');
});
http://jsfiddle.net/J9kAV/

我想让section s在点击时变成黄色。然而,由于$('section')也可以引用它们的父元素,它也将CSS应用于它们。

我怎样才能告诉jQuery只对被点击的子元素应用CSS而不是父元素?

我不想使用$('section section'),因为我也希望父元素变成黄色,如果他们被特别点击。所以我需要一个JavaScript/jQuery解决方案,而不是一个选择器或HTML解决方案。

使用

e.stopPropagation();

例子: http://jsfiddle.net/8KLEK/

试试这个:

$('section').click(function(e){
    e.stopImmediatePropagation();
    $(this).css('color','yellow');
});

正确的方法是将'this'改为'e.target';

$('section').click(function (e) {
    $(e.target).css('color','yellow'); 
});
http://jsfiddle.net/J9kAV/5/

关于为什么这个工作的更多信息。https://developer.mozilla.org/en-US/docs/Web/API/event.target