Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

jquery - Javascript add function call with parameters to button

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

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

1 Reply

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...