问题
I'm struggling to find out why the setTimeout
function cannot find my radio button tagging function when trying to run.
this is my code...
var radioButtonTagging = (function(){
console.log('run');
$("span.radio").each(function(i, ele){
$(ele).addClass('radio'+i);
});
$(".radio1").click(function(){
console.log('fired');
$('#expandQuestion1').css('display','block');
});
});
if($('span.radio').length){
console.log('run');
radioButtonTagging();
} else {
console.log('trying to run timer');
setTimeout("radioButtonTagging()",2000);
}
http://pastebin.com/nvacxZGS
I'm basically just looking for spans with a class radio and adding a further class with radio plus the index.
The reason why I'm using the setInterval is because when it tries to fire the first time the span's are not in place as they are being inserted via jquery.. so are not finished during doc.ready..
Any help would be great
回答1:
You are passing a string to setInterval
, so it is evaled in a different scope. Since the function you are looking for is scoped locally, it can't find it.
Don't pass strings to setInterval
, pass functions.
回答2:
try this
setTimeout(function(){ radioButtonTagging() },2000);
回答3:
Try: setTimeout(radioButtonTagging, 2000);
See here: http://jsfiddle.net/qUAZf/
来源:https://stackoverflow.com/questions/5804112/function-is-undefined