为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

潇湘沐 2021-10-07 20:11:39
在 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);
查看完整描述

2 回答

?
繁花不似锦

TA贡献1851条经验 获得超4个赞

解决此问题的一种方法是查看外部事件侦听器的事件目标。


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

虽然这确实需要从罗马数字映射到常规数字,但这样您只需添加一个事件侦听器!


查看完整回答
反对 回复 2021-10-07
?
沧海一幻觉

TA贡献1824条经验 获得超5个赞

如果你真的想保持这样的代码逻辑并且只想重构,我会这样做:


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 似乎很奇怪。


查看完整回答
反对 回复 2021-10-07
  • 2 回答
  • 0 关注
  • 146 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信