admin管理员组文章数量:1434889
Here's the code:
window.onload = function() {
oldonload && oldonload();
function test() {
alert("meh");
}
$('input[type=file]').change(test());
}
The code is fairly straight forward, test()
is called only when input[type=file]
is changed. However test()
is being called whenever my page is loaded.
What is going on here? How would I execute the function only when user interacts with the input element?
Here's the code:
window.onload = function() {
oldonload && oldonload();
function test() {
alert("meh");
}
$('input[type=file]').change(test());
}
The code is fairly straight forward, test()
is called only when input[type=file]
is changed. However test()
is being called whenever my page is loaded.
What is going on here? How would I execute the function only when user interacts with the input element?
Share Improve this question edited Aug 21, 2020 at 12:33 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked May 11, 2016 at 6:11 Joel MinJoel Min 3,4573 gold badges22 silver badges38 bronze badges 1- It happens on load, because you said it so, use onclick. – Bálint Commented May 11, 2016 at 6:13
4 Answers
Reset to default 7You are calling the method on this line:
$('input[type=file]').change(test());
Change it to:
$('input[type=file]').change(test);
If you want to pass a parameter to test
:
var myVar = 5;
$('input[type=file]').change(function () {
test(myVar);
});
Just change the file change event like this :
$('input[type=file]').change(function() { test() });
You're executing the function immedietaly instead of assigning a handler. You should instead do:
$('input[type=file]').change(test);
change takes function as argument, so you just need to provide function name to be called.
$('input[type=file]').change(test);
本文标签: javascriptWhy is my JS function executed onload instead of onchangeStack Overflow
版权声明:本文标题:javascript - Why is my JS function executed onload instead of onchange? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745644996a2668081.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论