我正在尝试通过window对象访问一个函数。在我的代码中,我的函数被字符串引用,所以我必须使用window对象(或eval)来获取它。我用纯JavaScript测试了我的代码,它运行得很好。但是当使用jQuery时它失败了。这是我的测试代码:
function speak(words, callback){
for(var i=0;i<10000;i++){
console.log(words);
}
if(callback)
callback.call();
}
console.log(window['speak']);
Here is a link to the pure JavaScript version which works.
Here is a link to the jQuery version which doesn't work.
我需要做些什么才能在jQuery中使用它?
答案 0 :(得分:5)
您没有将speak
声明为window
的成员,而JSFiddle实际上将其包含在document.ready
回调中。 You'll need to explicitly set window.speak = speak
as part of your code if you want it available on the window
object
或者,您需要将小提琴配置为execute without a wrapper rather than onDomReady