Frage

Ich möchte alle passenden Elemente entfernen, aber überspringen Sie die erste Instanz jedes Spiels:

// 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>

Irgendwelche Vorschläge?

  • Verwendung jQuery() statt $() Wegen des Konflikts mit 'Legacy' Code
  • Verwendung .empty() Weil .a enthält js, die ich deaktivieren möchte
  • Mit JQuery 1.2.3 festsitzen

Danke!

War es hilfreich?

Lösung

Probieren Sie es aus:

$('.a:gt(0), .b:gt(0)').remove();

Ich bin mir nicht sicher, ob es mit dem möglich ist, sie zu einem Selektor zu kombinieren :gt(), Es kann den Umfang ändern und alle nach dem ersten entfernen .a.

Andere Tipps

Es sieht so aus, als ob Ihr HTML falsch ist. Ich habe es an Folgendes geändert:

<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>

Dann schien dies zu funktionieren:

jQuery('div#scope div.a').not(':first').empty();
jQuery('div#scope div.b').not(':first').empty();
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top