简体   繁体   English

如何通过使用onclick事件中的函数并使用循环从函数中的数组中计数函数来调用多个JavaScript函数?

[英]How to call multiple JavaScript functions by using function in onclick event and using loop to count functions from array in function?

How to call multiple JavaScript functions by using function in onclick event and using loop to count functions from array in function? 如何通过使用onclick事件中的函数并使用循环从函数中的数组中计数函数来调用多个JavaScript函数? Demonstration: 示范:

var arr = [function one(){console.log("one")}, function two(){console.log("two")} ];

htmlElement.onclick = function(){
  for(var i = 0, a = arr.length; i < a; i++ ){
  }
}

Simple - don't use onclick - it's brittle (especially when used inline within HTML) and harks back to how JS was written in the '90s. 简单-不要使用onclick它很脆弱(尤其是在HTML中内联使用时),让人回想起90年代JS的编写方式。

Use addEventListener instead: 使用addEventListener代替:

arr.forEach(function(callback) {
    htmlElement.addEventListener('click', callback);
});
for(var i = 0,a = arr.length; i<a; i++){
    arr[i]();
}

This should work. 这应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM