Function is undefined?

喜你入骨 提交于 2019-12-11 07:44:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!