![](/img/trans.png)
[英]Javascript: var myFunc = function() vs. var myFunc = function myFunc()
[英]Reference error: myFunc is not a function
我的函數出現問題,顯示類型錯誤。 總之,我的代碼如下:
function myFunc(){
alert('test');
}
//if I run myFunc() here then it runs
myFunc();//alerts test
$('.selector').click(function(){
myFunc();//type error:: how to call the function?
});
抱歉,如果這是一個愚蠢的問題。
更新資料
我剛剛重現了我的關鍵問題:
window.onload = function(){
function myFunc(){
alert('test');
}
}
$('.test').click(function(){
myFunc();//doesn't alert test
});
myFunc
的作用域是在內部聲明的函數。
將其移到外部或將事件處理程序分配移到內部。
// Define this in a script element after the element you are trying to select
function myFunc(){
alert('test');
}
$('.test').click(function(){
myFunc();
});
// or use this anywhere
window.onload = function(){
function myFunc(){
alert('test');
}
$('.test').click(function(){
myFunc();
});
}
// but if you are going to use jQuery, you might as well go the whole hog
// and also just wait for the DOM to be ready instead of allowing time for images
// and other external resources to load too.
$(function(){
function myFunc(){
alert('test');
}
$('.test').click(function(){
myFunc();
});
});
您的函數在另一個函數的范圍內定義,並且無法訪問。 您應該將其放在調用函數的范圍內,例如:
function myFunc() {
alert('test');
}
$(function() {
$('.test').click(function() {
myFunc();
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.