Javascript function cannot be found
我在document.ready()中有以下代码
1 2 3 4 5 6 7 8 9 | if ($("#site-master").length > 0) { setMinContentHeight(); function setMinContentHeight() { // removed for clarity } } |
我只是检查页面是否正确(#site-master),然后调用我的最小高度函数,但是我在firebug中遇到以下错误:ReferenceError:setMinContentHeight未定义。
我不是javascript专家,但这怎么可能呢? 如果我将它移到document.ready()之外,该函数可以工作。 我已经检查过了if语句中的代码。
此外,这是实现我想要的最佳方式吗?
提前致谢。
永远不要在
1 2 3 4 5 6 7 | function setMinContentHeight() { // removed for clarity } if ($("#site-master").length > 0) { setMinContentHeight(); } |
如果我们解决ECMAScript规范,根据第12章,
因此,遵循语义部分的注释:
Several widely used implementations of ECMAScript are known to support
the use ofFunctionDeclaration as aStatement . However there are
significant and irreconcilable variations among the implementations in
the semantics applied to such FunctionDeclarations. Because of these
irreconcilable differences, the use of aFunctionDeclaration as a
Statement results in code that is not reliably portable among
implementations. It is recommended that ECMAScript implementations
either disallow this usage ofFunctionDeclaration or issue a warning
when such a usage is encountered. Future editions of ECMAScript may
define alternative portable means for declaring functions in a
Statement context.
这意味着我们无法保证在这种情况下的一致行为,因此,如果在语句中声明了函数,我们将始终在
首先,阅读
把它放在
1 2 3 4 5 6 7 8 | // here if ($("#site-master").length > 0) { setMinContentHeight(); } // or here: function setMinContentHeight() { … } |
1 2 3 4 5 6 | if ($("#site-master").length > 0) { setMinContentHeight(); } function setMinContentHeight() { // removed for clarity } |
您需要在全局范围内声明您的函数。
在定义函数后放置调用,并且不在if块中定义函数:
1 2 3 4 5 6 7 | function setMinContentHeight() { // removed for clarity } if ($("#site-master").length > 0) { setMinContentHeight(); } |
也许你有浏览器兼容性问题,但它的工作原理如下:
对:
1 2 | n(); function n(){ alert('1'); } |
错误:
1 2 | n(); var n = function(){ alert('1'); } |