删除jQuery中的元素

时间:2017-02-02 07:04:04

标签: javascript jquery dom

这是DOM,这里有一个删除父项的按钮:

<i class="fa fa-times remove-product-compare" aria-hidden="true"></i>

这是我的DOM:

<div class="col-lg-12 col-md-12 col-xs-12 pull-right comp-container" style="padding: 0;margin: 10px 0 10px 0;">
<div class="col-lg-3 col-xs-12 col-md-3 pull-right compareProduct">
    <h3 style="text-align: right;">
product
    </h3>
    <i class="fa fa-times remove-product-compare" aria-hidden="true"></i>
    <img src="images/photos/6.jpg" class="img-thumbnail img-responsive" style="height: 250px;width: 100%" />
</div>
<div class="col-lg-3 col-xs-12 col-md-3 pull-right compareProduct">
    <h3 style="text-align: right;">
        product2
    </h3>
    <i class="fa fa-times remove-product-compare" aria-hidden="true"></i>
    <img src="images/photos/2.jpg" class="img-thumbnail img-responsive" style="height: 250px;width: 100%" />
</div>
<div class="col-lg-3 col-xs-12 col-md-3 pull-right compareProduct">
    <h3 style="text-align: right;">
        product3
    </h3>
    <i class="fa fa-times remove-product-compare" aria-hidden="true"></i>
    <img src="images/photos/3.jpg" class="img-thumbnail img-responsive" style="height: 250px;width: 100%" />
</div>

此Javascript代码应隐藏父级并正常工作:

$(".remove-product-compare").on("click",function (e) {
    $(this).parent().hide();
});

但是这段代码应该从DOM中删除父代并且不起作用:

$(".remove-product-compare").on("click",function (e) {
    $(this).parent().remove();
});

1 个答案:

答案 0 :(得分:0)

parent()方法返回所选元素的直接父元素。

$(function() {
$(".remove-product-compare").click(function (e) {
       $(this).parent().remove();
    });
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">


<div class="col-lg-12 col-md-12 col-xs-12 pull-right comp-container" style="padding: 0;margin: 10px 0 10px 0;">
<div class="col-lg-3 col-xs-12 col-md-3 pull-right compareProduct">
        <h3 style="text-align: right;">
product
        </h3>
        <i class="fa fa-times remove-product-compare" aria-hidden="true"></i>
        <img src="images/photos/6.jpg" class="img-thumbnail img-responsive" style="height: 250px;width: 100%" />
</div>
<div class="col-lg-3 col-xs-12 col-md-3 pull-right compareProduct">
    <h3 style="text-align: right;">
        product2
    </h3>
    <i class="fa fa-times remove-product-compare" aria-hidden="true"></i>
    <img src="images/photos/2.jpg" class="img-thumbnail img-responsive" style="height: 250px;width: 100%" />
</div>
<div class="col-lg-3 col-xs-12 col-md-3 pull-right compareProduct">
    <h3 style="text-align: right;">
        product3
    </h3>
    <i class="fa fa-times remove-product-compare" aria-hidden="true"></i>
    <img src="images/photos/3.jpg" class="img-thumbnail img-responsive" style="height: 250px;width: 100%" />
</div>