单击时隐藏div,但单击里面的图像时不执行任何操作

时间:2022-02-25 09:44:19

I have a div main-wrap and an image in it.

我有一个div主包和一个图像。

I want to hide main-wrap when click on it. But when you click on image that is inside main-wrap I don't want to do anything. Right now I have this non-working code. When I click on image main-wrap still hides. (hidden is my class .hidden {display:none})

我想在点击它时隐藏主要包装。但是当你点击main-wrap中的图像时,我不想做任何事情。现在我有这个不工作的代码。当我点击图像主包裹仍然隐藏。 (隐藏是我的班.hidden {display:none})

<div class="main-wrap" >
    <div class="photo-wrap">
        <img style="cursor:default;"  onclick = "return false;" class="img img-responsive" src = "/stat_photo/1.jpg"/>

    </div>
</div>

And I have this code

我有这个代码

 $(document).ready(function() {
   $('.main-wrap').click(function(){$('.main-wrap').addClass('hidden')});
 });

3 个解决方案

#1


1  

$('.main-wrap').click(function(e) {
   $(this).addClass('hidden');
}).on('click', 'img', function(e) {
  return false;
});

https://jsfiddle.net/bfwsqxko/1/

added a click event, which extends with an exceptional click on image, which is set to return false;

添加了一个click事件,该事件通过对图像的特殊点击进行扩展,该图像被设置为返回false;

Thanks & regards

感谢和问候

#2


0  

I ended up with this code

我最终得到了这段代码

$('.main-wrap').on('click', function(e) {
                    $('.main-wrap').addClass('hidden');
                }).on('click', 'img', function(e) {
                    // clicked on descendant div
                    e.stopPropagation();
});

which is taken from here How to have click event ONLY fire on parent DIV, not children? (the accepted answer didn't work though)

从这里获取如何点击事件只对父DIV,而不是孩子? (虽然接受的答案不起作用)

#3


-1  

Better add an id of the image. Then replace .img with #yourid

最好添加图像的ID。然后用#yourid替换.img

  $(document).ready(function() {
          $('.main-wrap').not('.img').click(function(){$('.main-wrap').addClass('hidden')});
        });

#1


1  

$('.main-wrap').click(function(e) {
   $(this).addClass('hidden');
}).on('click', 'img', function(e) {
  return false;
});

https://jsfiddle.net/bfwsqxko/1/

added a click event, which extends with an exceptional click on image, which is set to return false;

添加了一个click事件,该事件通过对图像的特殊点击进行扩展,该图像被设置为返回false;

Thanks & regards

感谢和问候

#2


0  

I ended up with this code

我最终得到了这段代码

$('.main-wrap').on('click', function(e) {
                    $('.main-wrap').addClass('hidden');
                }).on('click', 'img', function(e) {
                    // clicked on descendant div
                    e.stopPropagation();
});

which is taken from here How to have click event ONLY fire on parent DIV, not children? (the accepted answer didn't work though)

从这里获取如何点击事件只对父DIV,而不是孩子? (虽然接受的答案不起作用)

#3


-1  

Better add an id of the image. Then replace .img with #yourid

最好添加图像的ID。然后用#yourid替换.img

  $(document).ready(function() {
          $('.main-wrap').not('.img').click(function(){$('.main-wrap').addClass('hidden')});
        });