jQuery .parent() 不会触发隐藏

jQuery .parent() won't trigger hide

我的 .parent() 选择器不适用于 .hide() 函数。 这是我的 HTML:

...
<div class="overpopup">
    <div class="overpopup--background">

    </div>
    <div class="overpopup--content">
        <img src="http://placehold.it/600x600?text=Overpopup">
    </div>
</div>
...

我的这一部分 jQuery:

$(document).ready(function() {
    ...
    $('.overpopup--background').click(function(){
        $(this).parent().hide();
    });
});

谁能发现我犯的错误?我尝试了不同的操作,例如添加 css 有效和那些有效。在 jQuery 中隐藏 parent 是否合法?如果没有,是否有简单的解决方法?

试试这个代码

$("body").on("click", ".overpopup--background", function() {
    $(this).parent().hide();
});

我猜,您正在通过 ajax

加载这些元素

将一些元素添加到您已应用点击的 div 中。

jsfiddle 你的代码:https://jsfiddle.net/jp14u8pc/2/

效果不错,

<div class="overpopup">
   <div class="overpopup--background">
     <p>
       Click Me
      </p>
   </div>
   <div class="overpopup--content">
     <img src="http://placehold.it/600x600?text=Overpopup">
   </div>
</div>

您的代码工作正常,但是您无法在您绑定的元素上激活点击事件,因为它没有设置宽度和高度。

给它设置宽度和高度或者添加一些元素就可以了。尝试点击下面的红色框,它会为您服务。

<div class="overpopup">
    <div class="overpopup--background" style="width:200px; height:200px; border:1px solid red;">
    </div>
    <div class="overpopup--content">
        <img src="http://placehold.it/600x600?text=Overpopup">
    </div>
</div>    

$(document).ready(function() {
    $('.overpopup--background').click(function(){
        $(this).parent().hide();
    });
});
div{margin:10px;}
.test{background:#FCE883; padding:10px;}
.overpopup{max-width:100%; height:auto; background:#333; color:#fff; padding:20px;}
.overpopup--background{width:auto; padding:5px 15px; background:navy; font-size:10px}
.overpopup--content{border:1px solid red; padding:10px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="test">
  test
<div class="overpopup">
    <div class="overpopup--background">
OVERPOPUP BACKGROUND BTN
    </div>
    <div class="overpopup--content">
        <img src="http://placehold.it/150x150?text=Overpopup">
    </div>
</div>
  </div>

我没有发现任何问题。您可以查看代码...。如果问题仍然存在,让我 know/view 您的代码。

隐藏 parent 是合法的!!!!!!,据我所知 jQuery 中没有这样的东西。因此,您可以隐藏任何元素,parent 或 child 或任何元素!唯一重要的是您如何隐藏和查看该元素。因为当你隐藏 parent 时,动作元素(这里是 overpopup--background)也隐藏在它的 parents 块中。