带参数的 onclick 分配函数 [英] onclick assigned function with parameters

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

问题描述

我不确定以前是否有人问过这个问题,因为我不知道它叫什么.

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.

添加括号时调用函数并将结果返回给 onclick

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

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

所以其实等于写

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

或使用绑定

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

然而,通常最好使用 addEventListener 来附加事件侦听器,但同样的原则也适用,它要么(不带参数)

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

bind 或匿名函数来传递参数等.

or bind or the anonymous function to pass arguments etc.

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

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

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