最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin7PV0评论

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);
Post a comment

comment list (0)

  1. No comments so far