【问题标题】:Firefox ignores child and jumps to parent on click eventFirefox 忽略子级并在点击事件时跳转到父级
【发布时间】:2017-07-07 06:25:39
【问题描述】:

以下代码在 Firefox 中无法正常运行,但在 chrome 中运行良好。

$("#parent").click(function(){
 alert("parent")
});

$("#child").click(function(){
 event.stopPropagation();
 alert("child")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="width:500px;height:500px;background:red;" id="parent">
 <div style="width:200px;height:200px;background:green; font-size:200px" id="child">
 X
 </div>
</div>

当我点击child时,firefox中触发了parent的click事件,child完全被忽略了。

我错过了什么吗?

我试图找到问题,但主要是关于传播的问题。

【问题讨论】:

  • 打开开发者工具(Firebug),在控制台查看错误信息

标签: jquery firefox cross-browser click parent


【解决方案1】:
$("#parent").click(function(e){
  if($(e.target).attr('id') == 'child'){
    //it's child
  } else {
    //its parent
  }
})

【讨论】:

    【解决方案2】:

    这是因为 event 在 Firefox 中未定义。 (在其他浏览器中,它可能默认为当前事件。)

    要修复它,请将event 作为参数添加到click 函数:

    $("#parent").click(function(){
      alert("parent")
    });
    
    $("#child").click(function(event){
      event.stopPropagation();
      alert("child")
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div style="width:500px;height:500px;background:red;" id="parent">
     <div style="width:200px;height:200px;background:green; font-size:200px" id="child">
     X
     </div>
    </div>

    【讨论】:

    • hmmm 所以缺陷在其他浏览器而不是 Firefox,有趣的是:)
    • 也许其他浏览器比 Firefox 更“友好”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多