Repeat Function X times
var xTcount = 3;
jQuery.fn.repeatFx = function(fn, times) {
for(var i = 0; i < times; i++) fn();
}
$("#Art_C_M li").live('click', function() {
var $this = $(this);
var target = $this.hasClass('Double_It') ? 'doubler'
: $this.hasClass('Float_R') ? 'floatR'
: null;
if (xTcount > 1) {repeatFx(target, xTcount);}
});
I'm trying to create a function that loops another function. Which function it loops varies though, i need a general function-looping function. I got help via this question: Iterate a script X times I didn't want to append it since it's old now, and i'm not sure if that's recommended.
xTcount does change, based on another script (the user clicks a series of divs that contain numbers, the value is parsed into an int and stored, but for simplicity i'll leave it as 3 in this question.)
doubler and floatR are the names of the functions. I was hoping to use a case solution to get the function names, and pass it to the loop function.
I have the if clause so that users don't always have to click "1" in order for the effect to occur. So开发者_开发问答 this way it only loops if it's greater than 1, and just once elsewise (which is taken care of in the base functions.)
EDIT
Modified code, to demonstrate a more explicit flow.
$(".Double_It").live('click', function() {
repeatFx(drawCard, xTcount);
});
It appears that my function isn't being called. I added an append(text) to my Doubling function, if i call the function directly, it works and i get the appended text as a signal that it fired. But via this loop function, the text never shows up. So I infer that the function isn't being called.
Remove the quotes from your function names and it should work:
var target = $this.hasClass('Double_It') ? doubler
: $this.hasClass('Float_R') ? floatR
: null;
Of course, if you get null back then your code is going to break so you might want to check for it:
if ((xTcount > 1) && (target !== null) {.....
See an equivalent mock up here at this JSFiddle
function a() { alert("a"); }
function b() { alert("b"); }
function c(f){ f();}
var x = 1; //change to '0' to see other function call
var fn = (x===0) ? a : b;
c(fn); //the alert will depend on whether a or b is assigned to fn
精彩评论