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
185 views
in Technique[技术] by (71.8m points)

javascript - onclick assigned function with parameters

I'm not sure if this has been asked before because I don't know what it's called.

But why wouldn't a method like this work? Below is just a general example

<script>
document.getElementById('main_div').onclick=clickie(argument1,argument2);

function clickie(parameter1,parameter2){
 //code here
}

</script>

The code above would work fine if the event handler was assigned without parameters, but with parameters, it doesn't work. I think I read online that to overcome this problem, you could use closures. I'm assuming it's because of the parentheses ( ) that is calling the function immediately instead of assigning it to the event?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Because you're calling the function immediately and returning the result, not referencing it.

When adding the parenthesis you call the function and pass the result back to onclick

document.getElementById('main_div').onclick = clickie(); // returns undefined

so it's actually equal to writing

document.getElementById('main_div').onclick = undefined;

which is not what you want, you want

document.getElementById('main_div').onclick = clickie;

but then you can't pass arguments, so to do that you could use an anonymous function as well

document.getElementById('main_div').onclick = function() {
    clickie(argument1,argument2);
}

or use bind

document.getElementById('main_div').onclick = yourFunc.bind(this, [argument1, argument2]);

It is however generally better to use addEventListener to attach event listeners, but the same principle applies, it's either (without arguments)

document.getElementById('main_div').addEventListener('click', clickie, false);

or bind or the anonymous function to pass arguments etc.

document.getElementById('main_div').addEventListener('click', function() {
    clickie(argument1,argument2);
}, false);

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

1.4m articles

1.4m replys

5 comments

57.0k users

...