【发布时间】:2012-01-03 10:50:51
【问题描述】:
我们允许用户编写有时会多次调用jQuery.ready(function(){..}) 的代码。似乎第一个引发错误的函数调用阻止了其余函数的执行。
曾讨论过这个here,解决方案是将jQuery.ready() 包装在一个委托中,而不是包装传递给jQuery.ready(..) 的匿名函数参数。
如何覆盖 jQuery.ready(fn) 并将传入的函数参数包装在一个委托中,该委托将其包装在 try/catch 中并传递给 jQuery.ready(delegate)?
这是一个例子:
<head>
<script>
// here is some code from third-party developer that sometimes throws an error
jQuery.ready(function() {
if ((new Date()).getMonth() == 0)
throw Error("It's January!");
});
</script>
</head>
<body>
<script>
// here is my code which should run regardless of the error in the <head> script
jQuery.ready(function() {
alert("I need to run even in January!");
});
</script>
</body>
我可以做些什么来让代码运行而不考虑错误?
【问题讨论】:
-
我们不能将代码包含在 try-catch 块中,因为该代码是由第三方开发人员提供的。这是引用讨论中的海报描述的类似问题。
标签: jquery error-handling