简体   繁体   English

我如何使用jQuery获取除最后一个元素以外的所有元素

[英]How can I get every element except the last one with jQuery

I have several divs 我有几个div

<div class="myClass"></div>
<div class="myClass"></div>
<div class="myClass"></div>
<div class="myClass"></div>

that are being generated dynamically. 是动态生成的。 When the button is clicked, I need to remove all divs with myClass class except the last one. 单击按钮后,我需要删除除myClass类之外的所有div,最后一个除外。 So far I have tried some variations of: 到目前为止,我已经尝试了以下几种变体:

$('.myClass').not($('.myClass').last()).remove();

OR 要么

$('.myClass').not($(this).last()).remove();

neither seem to work. 似乎都不起作用。 What am I doing wrong? 我究竟做错了什么?

尝试这种方式:

 $('.myClass:not(:last)').remove();

your code is running fine with no problems 您的代码运行正常,没有问题

You need to put it in $(document).ready(); 您需要将其放在$(document).ready();

here is demo https://jsfiddle.net/8w2jb1Lr/ 这是演示https://jsfiddle.net/8w2jb1Lr/

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

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