jQuery .each () مع محددات متعددة - تخطي ، ثم .empty () عناصر
-
21-09-2019 - |
سؤال
أرغب في إزالة جميع عناصر المطابقة ، لكن تخطي الحالة الأولى من كل مباراة:
// Works as expected: removes all but first instance of .a
jQuery ('.a', '#scope')
.each ( function (i) {
if (i > 0) jQuery (this).empty();
});
// Expected: removal of all but first instance of .a and .b
// Result: removal of *all* instances .a and .b
jQuery ('.a, .b', '#scope')
.each ( function (i) {
if (i > 1) jQuery (this).empty();
});
<div id="scope">
<!-- Want to keep the first instance of .a and .b -->
<div class="a">[bla]</div>
<div class="b">[bla]</div>
<!-- Want to remove all the others -->
<div class="a">[bla]</div>
<div class="b">[bla]</div>
<div class="a">[bla]</div>
<div class="b">[bla]</div>
...
</div>
أي اقتراحات؟
- استخدام
jQuery()
عوضا عن$()
بسبب الصراع مع رمز "إرث" - استخدام
.empty()
لان.a
يحتوي على JS أود تعطيل - عالق مع jQuery 1.2.3
شكرا لك!
المحلول
جرب هذا:
$('.a:gt(0), .b:gt(0)').remove();
لست متأكدًا مما إذا كان الجمع بينهم في محدد واحد ممكن مع :gt()
, ، قد يغير النطاق ويزيل كل منهم بعد الأول .a
.
نصائح أخرى
يبدو أن HTML الخاص بك غير صحيح. لقد قمت بتعديله إلى ما يلي:
<div id="scope">
<!-- Want to keep the first instance of .a and .b -->
<div class="a">[bla]</div>
<div class="b">[bla]</div>
<!-- Want to remove all the others -->
<div class="a">[bla]</div>
<div class="b">[bla]</div>
<div class="a">[bla]</div>
<div class="b">[bla]</div>
...
</div>
ثم يبدو أن هذا يعمل:
jQuery('div#scope div.a').not(':first').empty();
jQuery('div#scope div.b').not(':first').empty();
لا تنتمي إلى StackOverflow