Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I would like to add a function call including parameters to a HTML button via javascript. I know there are plenty of questions to this subject but none of the answers i found did work for me.

Note: My HTML and JS are in separate files which are correctly linked (the JS code works)

Problem: I can add the function call like this:

var $add  = $("#add");
$add.click(myFunction);

However $add.click(myFunction(i)); does not work.(Did also try with specific integer)

I have also tried it the following way:

document.getElementById('add').onclick = function() {myFunction(i);};

But like that the function does not even get applied to the button.

My function is defined in the JS file like this:

function myFunction(length) {

//do stuff with length I would notice

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
293 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use some thing like function bind or do it using handler:

$add.click(function(e){
  myFunction(i);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...