javascript - Why is my JS function executed onload instead of onchange? - Stack Overflow

Here's the code:window.onload = function() {oldonload && oldonload();function test() {aler

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
Add a ment  | 

4 Answers 4

Reset to default 7

You 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);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745644996a4637916.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信