简体   繁体   English

jquery删除div和以前的标签?

[英]jquery remove div and previous label?

These are some input fields which i need to remove, but i am not able to remove the label tag 这些是我需要删除的一些输入字段,但我无法删除标签标记

 <label class="prfx-row-title">Unique Selling Proposition </label>
 <div class="prfx-row-content">
     <input type="text" name="dynamic_usp[0][text]" placeholder="unique selling proposition " value="testing hello world" />
     <span class="remove button">Remove USP</span>
 </div>

$(".remove").live('click', function() {
            $(this).parent().remove();
            $(this).parent().prev('label.prfx-row-title').remove();
        });

Now only the div is remove but not the label? 现在只删除div但不删除标签?

Anyone? 任何人?

That's because when removing the div , it is no longer in the DOM, so the label is not a sibling anymore. 那是因为当删除div ,它不再在DOM中,因此标签不再是兄弟姐妹了。 remove the label first, then the div : 首先删除标签,然后删除div

$(".remove").live('click', function() {
     $(this).parent().prev('label.prfx-row-title').remove();
     $(this).parent().remove();
});

Or better : 或更好 :

$(".remove").live('click', function() {
     $(this).parent().prev('label.prfx-row-title').remove()
     .end().remove();
});

You can't remove prev() from something that is no longer there... so the easiest fix is just to rearrange the order... 你不能从不再存在的东西中删除prev() ......所以最简单的解决方法就是重新排列顺序......

$(".remove").live('click', function () {
    $(this).parent().prev('label.prfx-row-title').remove();
    $(this).parent().remove();
});

Also, if possible you might want to update the version of jquery you are using and use on() instead of live() . 此外,如果可能,您可能希望更新正在使用的jquery版本并使用on()而不是live() live() has been deprecated since 1.7 and removed since 1.9 live()自1.7以来已被弃用,自1.9以来被删除

JSFiddle 的jsfiddle


You could also consider changing your DOM to something like... 您还可以考虑将DOM更改为...

<div class="prfx-row">
    <label class="prfx-row-title">Unique Selling Proposition</label>
    <div class="prfx-row-content">
        <input type="text" name="dynamic_usp[0][text]" placeholder="unique selling proposition " value="testing hello world" /><span class="remove button">Remove USP</span>

    </div>
</div>

and that way you could just do.. 那样你就可以做..

$(this).closest("prfx-row").remove();

JSFiddle 的jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM