jQuery用下一个父节点的子节点替换内容

时间:2018-02-17 17:46:41

标签: jquery parent lightbox children replacewith

我想创建一个包含div内容的灯箱,而且找不到比现在自己做的更好的方法。 我想用下一个替换当前内容。这是我的代码:

<div class="gallery_pic">
    <div class="content">
        <div class="content_inner">
            <img src="img"/>
            <p>content text</p>
        </div>
        <div class="icon_right"></div>
        </div>
        <img src="img" />
   </div>

   <div class="gallery_pic">
        <div class="content">
            <div class="content_inner">
                <img src="img2"/>
                <p>content text</p>
            </div>
            <div class="icon_right"></div>
        </div>
        <img src="img2" />
    </div>    
</div>

<script>
    $('.gallery_pic').click(function(){
        $('.content', this).show(); 
    });

    $('.icon_right').click(function(){
        $('.content').replaceWith( ??? );
     });

</script>

单击图库时,会打开包含其内容的灯箱,当单击icon_right时,应显示下一个父项的下一个.content而不是当前父项。我该怎么做?

谢谢!

1 个答案:

答案 0 :(得分:0)

第一名虽然.icon_right属于.gallery_pic点击,但您需要event.stopPropagation()

第二名:您需要隐藏其他内容$('.content').hide();

<script>
    $('.gallery_pic').click(function(){
        $('.content').hide();         //<<<<<<<<
        $('.content', this).show(); 
    });

    $('.icon_right').click(function(event){
        event.stopPropagation();      //<<<<<<<<
        $(this).closest('.gallery_pic').next('.gallery_pic').click()
     });

</script>

使用.next('.gallery_pic')获取下一个元素..对于以前的元素,您可以使用.prev('.gallery_pic')

  

注意:制作灯箱的方法还有很多,但总的来说   取决于你打算做什么..上面的代码将适用   你的方式..但如果你需要另一种方式,你可以使用data属性   对于每个img,只使用一个灯箱来显示图像

你也可以添加

$('.content').click(function(event){
  event.stopPropagation();      //<<<<<<<<
});