使用jQuery删除下一个元素

3

我有以下的HTML代码

<div name="taskNotificationsDiv">
    <div class="notificationCard">
        <span class="taskNotificationClose">x</span>
        Test
    </div>
    <hr>
    <div class="notificationCard">
        <span class="taskNotificationClose">x</span>
        Test
    </div>
    <hr>
    <div class="notificationCard">
        <span class="taskNotificationClose">x</span>
        Test
    </div>
    <hr>
</div>

我有下面的脚本,当x被点击时,从父元素中移除该容器。

  $(".taskNotificationClose").click(function (){    
        
        this.parentNode.parentNode
        .removeChild(this.parentNode);       
       
        return false;
       });

我需要的是删除div容器下方的hr线。请有人帮忙看一下,并告诉我应该如何实现。
这里是fiddle链接[Fiddle][1]。
我试过以下代码,尝试找到最近的hr并将其从父元素中删除,但出现了错误。
[1]: https://jsfiddle.net/
 var $hr = $(this).next('hr');
 this.parentNode.parentNode.removeChild($hr);

感谢您![1]: https://jsfiddle.net/so3k2hpq/ 这是链接地址。
3个回答

4
你可以使用.next()函数。在处理JQuery中的问题时,更好的方法是:

$(".taskNotificationClose").click(function (){    
     $(this).parent().next("hr").remove();
     $(this).parent().remove(); 
     return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div name="taskNotificationsDiv">
    <div class="notificationCard" style="color:red;">
        <span class="taskNotificationClose">x</span>
        Test
    </div>
    <hr>
    <div class="notificationCard" style="color:blue;">
        <span class="taskNotificationClose">x</span>
        Test
    </div>
    <hr>
    <div class="notificationCard" style="color:green;">
        <span class="taskNotificationClose">x</span>
        Test
    </div>
    <hr>
</div>


嗨Majed,点击第一个“x Test”元素会删除第三个元素。 - Ritu
@Ritu 我不这么认为。我添加了颜色以便更加清晰明了。 - Majed Badawi

0

你可以将“hr”标签移动到每个

标签内。这样可以解决你的问题。


0

JQuery的.next(element)可以实现这个功能

$(".taskNotificationClose").click(function (){    
     $(this).parent().next("hr").remove();
     $(this).parent().remove(); 
     return false;
});

你之前出现错误的原因是在调用.next()之前先移除了第一个兄弟节点。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接