[英]Why can I not define functions in jQuery's document.ready()?
如果將它們放在document.ready()函數中,則函數的定義為未定義:
$(document).ready(function(){
function foo()
{
alert('Bar');
}
});
foo(); // Undefined
為什么會這樣? 我確定我只需要一些簡單的理解即可:)
不知道為什么在ready()
范圍內定義函數對您很重要,但是您可以通過預先聲明foo
使其起作用:
<html><head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
<script>
var foo; // Here's the difference
$(document).ready(function(){
foo = function ()
{
alert('Bar');
}
});
</script></head><body>
<input type="button" onclick="foo()" value="Click me">
</body></html>
顯然,您不能在ready()
之后立即從內聯腳本中調用foo()
,因為ready()
代碼尚未運行,但是您可以稍后再調用該函數。
只需確保在ready()
代碼運行之前,沒有任何東西可以嘗試調用foo()
(或使foo()
的初始聲明成為無害的函數)。
您可以,但是必須在ready()
方法的范圍內調用它們,否則當ready()
方法退出時它們會失去范圍。
例如,下面的代碼將起作用:
$(document).ready(function(){
function foo()
{
alert('Bar');
}
foo(); // still in the scope of the ready method
});
如果將它們放在非它們的范圍內,它們將以未定義形式出現。 如果您真的想在$(document).ready(...)范圍之外使用它們,則需要在外部聲明它們。 如:
var foo;
$(document).ready(function(){
foo = function()
{
alert('Bar');
}
});
foo(); // works now because it is in scope
希望這可以幫助。
您的函數在$(document).ready()
回調范圍內定義,無法從外部 看到 。 只能在內部的$(document).ready()
范圍之外定義函數。
<script>
$(document).ready(function(){
myfnc = function (param1, param2)
{
alert('Hello');
}
myfnc();
});
</script>
<input type="button" onclick="myfnc('arg1', 'arg2')" value="Click me">
只是另一個補充:
在$(document).ready()
函數內部聲明函數或變量時,在$(document).ready()
使用onclick()
綁定時將無法訪問這些函數或變量。
您可以將聲明移到$(document).ready()
之外,也可以在$(document).ready()
中使用$('#element').on('click', function() {})
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.