我的功能出现问题,显示类型错误。总之,我的代码如下:
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
});
答案 0 :(得分:0)
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();
});
});
答案 1 :(得分:-1)
您的功能在另一个功能的范围内定义且无法访问。你应该把它放在调用函数的范围内,例如:
function myFunc() {
alert('test');
}
$(function() {
$('.test').click(function() {
myFunc();
});
});