在Javascript中为每个按钮打印不同的警报消息

时间:2016-12-06 21:39:36

标签: javascript

我正在尝试打印每个按钮的提醒。按钮1!应该提醒一个独角兽',按钮2!应警惕" A Hug!"和按钮3!应警惕" Fresh Laundry"。相反,我得到了#34; Fresh Laundry"对于每个按钮。

  <button id="btn-0">Button 1!</button>
  <button id="btn-1">Button 2!</button>
  <button id="btn-2">Button 3!</button>

  <script type="text/javascript">
    var prizes = ['A Unicorn!', 'A Hug!', 'Fresh Laundry!'];
    for (var btnNum = 0; btnNum < prizes.length; btnNum++) {
      var position = prizes[btnNum]
        // for each of our buttons, when the user clicks it...
        document.getElementById('btn-' + btnNum).onclick = function() {
            // tell her what she's won!
            alert(position);
        };
    }
  </script>

如何让每个按钮打印出正确的警报?

1 个答案:

答案 0 :(得分:1)

将事件处理程序放在闭包中,否则btnNum将始终是单击按钮时的最后一个。

&#13;
&#13;
var prizes = ['A Unicorn!', 'A Hug!', 'Fresh Laundry!'];
for (var btnNum = 0; btnNum < prizes.length; btnNum++) {
  (function(position) {
    document.getElementById('btn-' + btnNum).onclick = function() {
      // tell her what she's won!
      alert(position);
    };
  })(prizes[btnNum]);
}
&#13;
<button id="btn-0">Button 1!</button>
<button id="btn-1">Button 2!</button>
<button id="btn-2">Button 3!</button>
&#13;
&#13;
&#13;

或者,您可以使用let

&#13;
&#13;
var prizes = ['A Unicorn!', 'A Hug!', 'Fresh Laundry!'];
for (let btnNum = 0; btnNum < prizes.length; btnNum++) {
  let position = prizes[btnNum];
  document.getElementById('btn-' + btnNum).onclick = function() {
    // tell her what she's won!
    alert(position);
  };
}
&#13;
<button id="btn-0">Button 1!</button>
<button id="btn-1">Button 2!</button>
<button id="btn-2">Button 3!</button>
&#13;
&#13;
&#13;