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'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

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

1 Answer

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

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