【问题标题】:Determine last pressed in button array [duplicate]确定按钮阵列中的最后一次按下[重复]
【发布时间】:2018-05-05 05:54:51
【问题描述】:

我对 Web 开发非常陌生(来自 AV 控制系统编程背景),并且正在尝试做一些我确信必须非常简单的事情,但我做不到。基本上我已经在文档上创建了一个按钮数组变量,并且需要确定按下了哪个按钮。例如,假设我有四个 ID 为“id1”-“id4”的按钮,这是我在 JS 中得到的:

$(document).ready(function(){
    var sourceBtns = [];
    var lastPressedIndex;

   for(i=1;i<=4;i++){
       sourceBtns.push(document.getElementById("id"+i));
   }

   for(i=1;i<=sourceBtns.length;i++){
       sourceBtns[i-1].addEventListener("click",lastPressed);
   }

    function lastPressed(){      
       //need to assign lastPressedIndex here
   }
});

【问题讨论】:

  • console.log(this)
  • 如果你有像 id1, id2,id3 这样的 ID,那么你可以使用 jquery 选择器 $("button[id^='id']").on('click', function (){console.log(this)}),这样就可以得到最后按下的按钮
  • 我不认为这个问题的重复是非常相关的,这可能更有用:stackoverflow.com/questions/10291017/…

标签: javascript jquery


【解决方案1】:

这是你要找的吗?

$(document).ready(function() {
  var sourceBtns = [];
  var lastPressedIndex;

  $("button[id^='id']").click(function() {
    lastPressedIndex = this.id;
    console.log(lastPressedIndex);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="id1">1</button>
<button type="button" id="id2">2</button>
<button type="button" id="id3">3</button>
<button type="button" id="id4">4</button>

【讨论】:

  • 您编写的代码是正确的,但仅使用 $('botton') 也会将点击事件附加到其他按钮,所以这里的 ID 是递增的,所以我们将使用 $("button[id^= 'id']") 以避免其他按钮触发点击事件
  • @AbidNawaz 这是一项改进,感谢您的添加。我首先说明了最简单的解决方案,当然可以随时扩展。
  • $(this).attr("id") 可以简单地为this.id
  • @Taplar 谢谢,用你的简化更新了代码。
猜你喜欢
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
  • 2019-08-28
  • 2020-03-06
  • 2012-04-30
  • 2015-02-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多