为什么我的 JS 函数执行的是 onload 而不是 onchange?
Why is my JS function executed onload instead of onchange?
代码如下:
window.onload = function() {
oldonload && oldonload();
function test() {
alert("meh");
}
$('input[type=file]').change(test());
}
代码相当简单,test()
仅在 input[type=file]
更改时调用。但是,每当我的页面 加载 .
时,就会调用 test()
这是怎么回事?如何仅在用户与输入元素交互时才执行该功能?
您正在调用此行的方法:
$('input[type=file]').change(test());
改为:
$('input[type=file]').change(test);
如果要传递参数给test
:
var myVar = 5;
$('input[type=file]').change(function () {
test(myVar);
});
只需像这样更改文件更改事件:
$('input[type=file]').change(function() { test() });
您正在立即执行函数,而不是分配处理程序。你应该改为:
$('input[type=file]').change(test);
change 将函数作为参数,因此您只需提供要调用的函数名称即可。
$('input[type=file]').change(test);
代码如下:
window.onload = function() {
oldonload && oldonload();
function test() {
alert("meh");
}
$('input[type=file]').change(test());
}
代码相当简单,test()
仅在 input[type=file]
更改时调用。但是,每当我的页面 加载 .
test()
这是怎么回事?如何仅在用户与输入元素交互时才执行该功能?
您正在调用此行的方法:
$('input[type=file]').change(test());
改为:
$('input[type=file]').change(test);
如果要传递参数给test
:
var myVar = 5;
$('input[type=file]').change(function () {
test(myVar);
});
只需像这样更改文件更改事件:
$('input[type=file]').change(function() { test() });
您正在立即执行函数,而不是分配处理程序。你应该改为:
$('input[type=file]').change(test);
change 将函数作为参数,因此您只需提供要调用的函数名称即可。
$('input[type=file]').change(test);