2010-10-11 15 views
21

Ich habe eine dynamische Liste und muss das vorletzte Element auswählen.jquery selector vorletzten

<ul class="album"> 
    <li id='li-1'></li> 
    <!-- ... --> 
    <li id='li-8'></li> 
    <li id='li-9'></li> 
    <li class='drop-placeholder'>drag your favorites here</li> 
</ul> 

var lastLiId = $(".album li:last").attr("id"); // minus one? 

Antwort

59

Sie .eq() mit einem negativen Wert verwenden (-1 ist zuletzt) ​​n vom Ende zu bekommen, wie folgen aus:

$(".album li").eq(-2).attr("id"); // gets "li-9" 

You can test it here.

+0

aha, eq wird negativ! – FFish

+0

@richsage - Sie tun :) "Eine negative Zahl gibt eine Position an, die am Ende des Satzes beginnt, anstatt am Anfang", stellen Sie sicher, dass Sie sich die '.eq()' docs ansehen und nicht die ': eq() 'docs: http://api.jquery.com/eq/ –

15

Wahrscheinlich eine ordentliche Art und Weise aber, wie etwa:

var lastLiId = $(".album li:last").prev("li").attr("id");