代码之家  ›  专栏  ›  技术社区  ›  aviraldg Ortiga

如何检查父元素中的单击,而不是子元素中的单击?

  •  4
  • aviraldg Ortiga  · 技术社区  · 14 年前

    代码:

    HTML

    <!-- snip -->
    <div class="parent" id="parent">
        <div class="child" id="child">
        </div>
    </div>
    <!-- snip -->
    

    JavaScript

    /* snip */
    $(function () {
        $("#parent").click(function () {
            alert("This dialog should only show up if the parent is clicked.");
        });
    });
    /* snip */
    

    (这只是实际代码的基本结构…实际代码中的某些内容不同,例如子元素是jquery ui可拖动元素)

    2 回复  |  直到 14 年前
        1
  •  9
  •   PleaseStand    14 年前

    javascript/dom事件的工作方式是它们从孩子“冒泡”到家长。所以您只需要在子元素中停止它:

    $('#child').click(function(event) {
        event.stopPropagation();
    });
    

    jQuery documentation for .click() 更多信息。或者,您可以检查源元素在父元素的事件处理程序中是什么。 using event.target .

        2
  •  0
  •   Peter C    14 年前

    嗯,我会这样做的:

    $("#child").click(function() { });
    

    虽然这看起来有点难看,但我认为它肯定能起作用。