代码之家  ›  专栏  ›  技术社区  ›  Elie

如何在单击子对象时忽略单击事件

  •  26
  • Elie  · 技术社区  · 15 年前

    <div id="block">
    Sample text.
    <a href="#">Anchor link</a>
    </div>
    
    <script type="text/javascript">
        $("#block").click(function() { alert('test'); });
    </script>
    

    谢谢

    5 回复  |  直到 15 年前
        1
  •  31
  •   Nick Craver    15 年前

    您可以使用一个附加的处理程序来阻止链接中的点击,如下所示:

    $("#block a").click(function(e) { e.stopPropagation(); });
    

    我们在评论中讨论的备选方案是:

    $("#block").delegate('a', 'click', function(e){ e.stopImmediatePropagation(); })
               .click(function() { alert('test'); });​
    

    .stopImmediatePropagation() .

        2
  •  14
  •   Alexander    13 年前

    这就是你需要的: http://api.jquery.com/event.target/ .

    只是比较一下,看看这个元素是由你想要的元素触发的还是它的一个子元素触发的。

        3
  •  6
  •   Felix Kling    15 年前

    您可以测试使用 target 事件对象的属性:

    $("#block").click(function(event) { 
        if(event.target.nodeName != 'A') {
            alert('test');
        }
    });
    

    我建议你读书 Event Properties from quirksmode.org .

        4
  •  3
  •   methodin    15 年前
    $("#block").click(function(event) {
        if($(event.target).attr('id') == $(this).attr('id'))
        {
            alert('test');
        }
    });
    
        5
  •  0
  •   Aaron Digulla    12 年前

    这是一个演示( jsfiddle )包含一个窗体和两个字段:

    <div id="container">
        <form>
            <div class="field">
                <input id="demo" type="text" name="demo" />
            </div>
            <div class="field">
                <input id="demo2" type="text" name="demo2" />
            </div>
        </form>
    </div>
    

    代码如下所示:

    $(document).ready(function() {
        $('#container').click(function(evt) {
            if(this == evt.target) {
                console.log('clicked container',evt.target);
                $('#demo').focus();
            } else {
                console.log('clicked child -> ignoring');
            }
        });
    
        $('.field').click(function(evt) {
            if(this == evt.target) {
                console.log('clicked field div',evt.target);
                $(this).find('input').focus();
            } else {
                console.log('clicked child -> ignoring');
            }
        });
    });
    

    可以单击包含表单的容器将焦点设置在第一个输入字段上,也可以单击输入字段后面的容器将焦点设置到其中。

    如果单击该字段,则单击将被忽略。

    由于jQuery将DOM节点分配给 this

    this == evt.target
    

    #container {
        width: 600px;
        height: 600px;
        background: blue;
    }
    
    .field {
        background: green;
    }