简体   繁体   English

删除使用jQuery动态创建的元素

[英]Removing element created dynamically with jQuery

I created a element and text with jQuery to overlay another element: 我使用jQuery创建了一个元素和文本来覆盖另一个元素:

$("<div></div>").text("winner")
                .css( {position:"absolute", top:"48%", left:"40%", zIndex:9999} )
                .appendTo( $(".square2").css({position:"relative"}) )

Afterwards I need to remove it, so I checked the position of the element in Chrome: 之后,我需要将其删除,因此我检查了元素在Chrome中的位置:

<div class="square2">
   <p>Something</p>
   <p>Something</p>
   <table></table>
   <div>winner</div>
</div>

And finally I tried to remove selecting it as last child: 最后,我试图删除选择它作为最后一个孩子的方法:

$("div.square:last-child").remove();

But it removes all the children of div.square, not only the last one.(???) 但这会删除div.square的所有子项,而不仅仅是最后一个。(???)

You can use it: 您可以使用它:

var el = $("<div></div>").text("winner")
                    .css({
                            position:"absolute",
                            top:"48%",
                            left:"40%",
                            zIndex:9999,
                    });
    el.appendTo($(".square2").css({position:"relative"}));
    el.remove();

To remove the last div inside .square you could use : 要删除.square中的最后一个div,您可以使用:

$("div.square div:last-child").remove();

Hope his helps. 希望他的帮助。

 $("div.square div:last-child").remove(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="square"> <p>Something</p> <p>Something</p> <table></table> <div>winner1</div> <div>winner2</div> <div>winner3</div> </div> 

 $(document).ready(function(){ $("<div>winner1</div>") .css({ position:"absolute", top:"48%", left:"40%", zIndex:9999, }).appendTo($(".square2").css({position:"relative"})); /*binding the rmeove on click of button. Can change it according to your needs.*/ $("#remove").click(function(){ $('.square2 div:last-child').remove(); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="square2"> <p>Something</p> <p>Something</p> <table></table> <div>winner</div> </div> <button type="button" id="remove">Remove</button> 

Hope this helps. 希望这可以帮助。

If you're okay with a pure jQuery answer, you could use the following: 如果您可以使用纯jQuery的答案,可以使用以下方法:

$('.square').children().filter('div').last().remove()

This will take the element(s) with class square , select all it's(or their) children, filter so only the div elements are still selected, narrow that down by only selecting the last element in that list, and then finally remove that element. 这将使用具有square类的元素,选择其所有子元素,或进行过滤,以便仅仍选择div元素,通过仅选择该列表中的最后一个元素来缩小范围,最后删除该元素。 。 Hope this is what you were looking for. 希望这就是您想要的。

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

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