Jquery: How to pass in .next or .prev as a function variable?
In my code below, I want to be able to pass i开发者_StackOverflown prev or next. I basically just want to know how to make pn into a variable in my function(I tried below but its wrong), so i can do this:
doSlide($('UL li:last'), 0, next)
or
doSlide($('UL li:last'), 15, prev)
function:
function doSlide(current, px, pn) {
$(current).animate({
right: px
},200);
setTimeout(function(){
doSlide($(current)."+ pn +"('li'), px);
},45);
}
I'd send the functions as strings like this:
doSlide($('UL li:last'), 15, "next")
or
doSlide($('UL li:last'), 15, "prev")
And the function would be:
function doSlide(current, px, pn) {
$(current).animate({
right: px
},200);
setTimeout(function(){
doSlide($(current)[pn]('li'), px);
},45);
}
Try it. It works.
Hope this helps. Cheers
Further to your code and @Edgar Villegas Alvarado's answer, the problem is that you never check if there's anything returned by .next()
or .prev()
, therefore your recursion will never end, it will keep firing your function on empty jQuery objects every 45ms.
Use this:
function doSlide(current, px, pn) {
$(current).animate({
right: px
},200);
var $next = $(current)[pn]('li');
if($next.length){
setTimeout(function(){
doSlide($next, px);
},45);
}
}
doSlide($('ul li:first'), 15, "next");
// or
doSlide($('ul li:last'), 15, "prev");
精彩评论