admin管理员组

文章数量:1290994

I need to use the 1.3.2 library which unfortunately does not support the last functionality. This causes my function to fail:

$op.last().next().after($op);

"$op.last is not a function"

Demo:

/

I have been unsuccessful at rewriting this functionality in pure js, any suggestions? Note, I will also need the .first(), but I'm assuming I will be able to extrapolate that from the .last alternate code. Many thanks-

I need to use the 1.3.2 library which unfortunately does not support the last functionality. This causes my function to fail:

$op.last().next().after($op);

"$op.last is not a function"

Demo:

http://jsfiddle/uscyH/

I have been unsuccessful at rewriting this functionality in pure js, any suggestions? Note, I will also need the .first(), but I'm assuming I will be able to extrapolate that from the .last alternate code. Many thanks-

Share Improve this question edited May 18, 2012 at 13:18 Joe Riggs asked May 18, 2012 at 13:17 Joe RiggsJoe Riggs 1,3244 gold badges23 silver badges48 bronze badges 1
  • 2 then use a more recent jQuery – Joseph Commented May 18, 2012 at 13:18
Add a ment  | 

5 Answers 5

Reset to default 11

You can use the :last selector, which existed since 1.0:

$op.filter(':last')

To get the last element, do this:

$op.slice( -1 )

Live demo: http://jsfiddle/uscyH/4/

The jQuery .slice() method is patterned after the JavaScript .slice() method for arrays. One of the features that it mimics is the ability for negative numbers to be passed as either the start or end parameter. If a negative number is provided, this indicates a position starting from the end of the set, rather than the beginning.

Source: http://api.jquery./slice/


To get the first element do this:

$op.eq( 0 )

Live demo: http://jsfiddle/uscyH/5/

Assuming $op is the collection of options, get the first DOM element in the collection using:

var first = $op[0];

and the last using:

var last = $op[$op.length-1];

It looks like you could find the last or first item with this method http://jsfiddle/uscyH/3/

alert("Last is: "+$("option:last").html()+" and first is: "+$("option:first").html());​

Update: Looks like you have lots of ideas to choose from now. Feel free to use whatever approach you would like. This approach is probably not the fastest one since it is doing two DOM queries instead of operating on the list you already appear to have stored in an array. It's nice to see how jQuery has been so powerful even back in these versions. Thanks for the ideas everyone!

$($op[$op.length-1]).next().after($op);

You can also choose to extend jquery and create your own last method.

本文标签: javascriptAlternative to jQuery39s lastStack Overflow