猿问

有没有办法优化“addEventListener”代码块?

在 HTML 页面中,我有 7 个按钮带有以下 ID:#I、#II、#III、#IV、#V、#VI、#VII放置在rContainer div 中。我想设置与触摸按钮相关的iActiveButton变量。我的代码似乎工作正常,但我觉得它可以增强和缩短。任何的想法?


var iActiveButton;


function touchHandler(){

  console.log(iActiveButton);

}


rContainer.addEventListener("touchstart", function(){


  I.addEventListener("touchstart", function(){iActiveButton = 1;}, false);

  II.addEventListener("touchstart", function(){iActiveButton = 2;}, false);

  III.addEventListener("touchstart", function(){iActiveButton = 3;}, false);

  IV.addEventListener("touchstart", function(){iActiveButton = 4;}, false);

  V.addEventListener("touchstart", function(){iActiveButton = 5;}, false);

  VI.addEventListener("touchstart", function(){iActiveButton = 6;}, false);

  VII.addEventListener("touchstart", function(){iActiveButton = 7;}, false);


  touchHandler();


}, false);


潇湘沐
浏览 147回答 2
2回答

繁花不似锦

解决此问题的一种方法是查看外部事件侦听器的事件目标。rContainer.addEventListener("touchstart", function(event){  const targetId = event.target.getAttribute('id');  // don't set iActiveButton if you clicked empty space inside `rContainer`  if (targetId) {    // romanNumeralMap looks like { 'I': 1, 'II': 2, etc... }    iActiveButton = romanNumeralMap[targetId];  }  touchHandler();}, false);虽然这确实需要从罗马数字映射到常规数字,但这样您只需添加一个事件侦听器!

沧海一幻觉

如果你真的想保持这样的代码逻辑并且只想重构,我会这样做:const buttonArray = [I, II, III, IV, V, VI, VII];rContainer.addEventListener("touchstart", function(){  buttonArray.forEach((button, index) => {    button.addEventListener("touchstart", function(){iActiveButton = index;}, false);  }  touchHandler();}, false);但我完全同意这些评论,在每个事件上添加新的 EventListeners 似乎很奇怪。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答