onclick assigned function with parameters(带参数的 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 分配函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带参数的 onclick 分配函数


- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- 400或500级别的HTTP响应 2022-01-01
- Flexslider 箭头未正确显示 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01