[英]Add two or more functions to an onclick event
I created an image element and added attributes to it. 我创建了一个图像元素并为其添加了属性。 I also added a function to an onclick event by doing: 我还通过执行以下操作向onclick事件添加了一个函数:
img.onclick = change;
Now I want to add another function which has a parameter to my onclick event. 现在,我想向onclick事件添加另一个具有参数的函数。 Lets say I want to add: 可以说我要添加:
retrieveClass(this.className);
How can I do this? 我怎样才能做到这一点? Something like... 就像是...
img.onclick = change, retrieveClass(this.className);
When you want to have multiple event handlers triggered by a single event, the standard method is to use addEventListener
( doc ). 当您希望一个事件触发多个事件处理程序时,标准方法是使用addEventListener
( doc )。
Assuming in your sample, change
is the name of a handler function, and retrieveClass(this.className)
returns another handler function, you could do this: 假设在您的示例中, change
是处理程序函数的名称, retrieveClass(this.className)
返回另一个处理程序函数,则可以执行以下操作:
img.addEventListener('click', change);
img.addEventListener('click', retrieveClass(this.className));
img.onclick = function () { change; retrieveClass(this.className); }
This is the simplest... 这是最简单的...
<img src="..." onclick="command1; command2;">
You should use a function for this: 您应该为此使用一个函数:
function imgClicked() {
command1;
command2;
}
Of course, you can declare it also with 当然,您也可以使用
img.onclick = function () { command1; command2; }
Create a wrapper function containing both function calls then bind that to your onclick. 创建一个包含两个函数调用的包装器函数,然后将其绑定到您的onclick。
function wrap() {
change;
retrieveClass(img.className);
}
img.onclick = wrap();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.