【问题标题】:jQuery on() stopPropagation not working?jQuery on() stopPropagation 不起作用?
【发布时间】:2012-02-18 04:22:29
【问题描述】:

我似乎无法让它停止传播..

  $(document).ready(function(){
      $("body").on("click","img.theater",function(event){ 
          event.stopPropagation();    
          $('.theater-wrapper').show();
      }); 

       // This shouldn't fire if I click inside of the div that's inside of the 
       // `.theater-wrapper`, which is called `.theater-container`, anything else it should.
       $(".theater-wrapper").click(function(event){
           $('.theater-wrapper').hide();
       }); 
  });

Refer this jsfiddle

【问题讨论】:

    标签: javascript jquery stoppropagation propagation


    【解决方案1】:

    由于您在body 元素上使用on,而不是直接在img.theater 上使用,因此事件将冒泡到body 元素,这就是它的工作原理。

    在事件冒泡的过程中.theater-wrapper 元素click 事件将被触发,所以你会看到它。

    如果您不创建任何动态元素,则直接在 img.theater 元素上附加点击事件处理程序。

    $("img.theater").click(function(event){
        event.stopPropagation();    
        $('.theater-wrapper').show();
    }); 
    

    或者,您可以在 .theater-wrapper 元素 click 处理程序中检查 click 事件的目标,并且什么也不做。

    $(".theater-wrapper").click(function(event){
        if ($(event.target).is('img.theater')){
             event.stopPropagation();
             return;
        }
        $('.theater-wrapper').hide();
    }); 
    

    【讨论】:

    • 我所有的内容都是通过ajax加载到页面中的
    • @DylanCross - 在这种情况下,您应该使用我在回答中提到的替代方法。保持 on 事件处理不变。
    • 是的,当我点击它不应该关闭的地方时,它仍然会关闭。
    • 你能检查一下 console.log($(event.target)) 给你什么吗?
    • img 和 div.image-wrapper 和 div.theater-wrapper
    【解决方案2】:

    最好的方法是:

    $(".theater-wrapper").click(function(event){
        if (!$(event.target).is('img.theater')){
            $('.theater-wrapper').hide();
        }
    }); 
    

    手风琴和复选框对我有用

    【讨论】:

      【解决方案3】:

      使用 event.stopImmediatePropagation() 它对我有用

      【讨论】:

        【解决方案4】:

        响应您的 jsfiddle @Dylan

        这里:当您单击白点时,它不应该关闭。 jsfiddle.net/Cs8Kq - 迪伦

        改变

        if ($(event.target).is('img.theater')){
        

        if ($(event.target).is('.theater-container')){
        

        它会起作用的。

        我通过在事件处理程序中使用 console.log(event.target) 解决了这个问题,并且只使用了当我单击您所说的白色区域时退出的选择器。

        我本来会评论的,但我没有足够的星尘和硬币。

        编辑:像这样jsfiddle.net/heNP4/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-07-23
          • 1970-01-01
          • 2023-04-05
          • 2012-05-20
          • 2018-12-17
          • 1970-01-01
          • 2019-08-28
          相关资源
          最近更新 更多