Javascript jQuery:try catch { call function } 不起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4234944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery: try catch { call function } does not work?
提问by matt
I'm having a lot of JavaScript on my page and I'm using typekit. In order to make my page work correctly (grid and stuff) I'm using the new typekit font events.
我的页面上有很多 JavaScript,我正在使用 typekit。为了使我的页面正常工作(网格和东西),我使用了新的 typekit 字体事件。
It's simply a try and catch statement that checks if fonts get loaded or not. However somehow I'm not getting it. I'm calling the setGrid()
function if typekit fonts are loaded, but e.g. iPad or iPhone doesn't support that yet and so my page doesn't get properly shown when I don't call the setGrid()
function.
它只是一个 try 和 catch 语句,用于检查字体是否已加载。但是不知何故我没有得到它。setGrid()
如果加载了 typekit 字体,我将调用该函数,但例如 iPad 或 iPhone 尚不支持该功能,因此当我不调用该setGrid()
函数时,我的页面无法正确显示。
Anyway, I want to call the function in the error statement as well, so if the page is called on the iPhone, the page works without webfonts as well.
无论如何,我也想在错误语句中调用该函数,因此如果在 iPhone 上调用该页面,该页面也可以在没有 webfonts 的情况下工作。
try {
Typekit.load({
loading: function() { },
active: function() { setGrid(); },
inactive: function() { }
})
} catch(e) {
alert('error'); //works
setGrid(); //doesn't get called
}
However, the alert
works, the setGrid()
function doesn't get called.
Any ideas?
但是,alert
有效,该setGrid()
函数不会被调用。有任何想法吗?
edit: the function looks like that:
编辑:函数看起来像这样:
var setGrid = function () {
$('#header, #footer').fadeIn(500);
return $("#grid").vgrid({
easeing: "easeOutQuint",
time: 800,
delay: 60
});
};
采纳答案by Shadow Wizard is Ear For You
Try making it "real" function, like this:
尝试使其成为“真实”功能,如下所示:
function setGrid() {
$('#header, #footer').fadeIn(500);
return $("#grid").vgrid({
easeing: "easeOutQuint",
time: 800,
delay: 60
});
};
回答by Mark Byers
The function does get called, but it just doesn't work as you expected causing you to think that it isn't getting called. You can see that it is getting called by adding an alert as the first line of setGrid.
该函数确实被调用了,但它并没有像您预期的那样工作,导致您认为它没有被调用。您可以看到通过在 setGrid 的第一行添加警报来调用它。
回答by icyrock.com
Can you:
你是否可以:
- try/catch around
setGrid
, too alert
after setGrid to confirm it's getting throughsetGrid
- try / catch语句周围
setGrid
,太 alert
在 setGrid 确认它通过之后setGrid