用参数onclick分配功能 [英] onclick assigned function with parameters

查看:137
本文介绍了用参数onclick分配功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道这是否曾被问过,因为我不知道它叫什么。



但是为什么不能像这样工作?以下只是一个简单的例子

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

函数clickie(parameter1,parameter2){
//此处的代码
}

< / script>

如果事件处理程序没有指定参数,上面的代码可以正常工作,但是使用参数,它不会没有工作。我想我在网上阅读,为了克服这个问题,你可以使用闭包。我假设这是因为括号()立即调用函数而不是将其分配给事件?

解决方案

因为您立即调用函数并返回结果,而不是引用它。



添加圆括号时,您调用该函数并将结果传递回onclick

  document.getElementById 'main_div')。onclick = clickie(); //返回undefined 

所以它实际上等于写入

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

这不是你想要的,你想要的

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

但是你不能传递参数,所以你必须使用匿名函数作为参数('main_div')。onclick = function(){
clickie(argument1,argument2) ;
}

通常使用addEventListener附加事件侦听器会更好,但是原理相同(不带参数)

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

或者传递参数的匿名函数

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


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?

解决方案

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 have to use an anonymous function as well

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

and it's 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 the anonymous function to pass arguments

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

这篇关于用参数onclick分配功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆