【问题标题】:Using more than one event in the same element in HTML在 HTML 的同一元素中使用多个事件
【发布时间】:2017-03-14 06:46:26
【问题描述】:

我试图在用户单击按钮和/如果用户按下回车键时触发功能。我不确定如何将两个事件存储在同一个元素中。

 <td> <input type= "button" disabled id ="e2" value="Exercise 2" onclick ="loadQsets(2);setRadioValues(2);disableInput() ;" /></td>

如何在同一个元素中同时使用 onclick 事件和 enter 键事件来触发同一个函数?

【问题讨论】:

  • 可以使用javascript的onkeypress事件

标签: javascript html function events


【解决方案1】:

您需要处理keydown 事件并将您的逻辑放在if statement

参见示例。 13Enter 的键码

document.getElementById('inp').addEventListener('keydown', function(e){
  if(e.keyCode === 13){
     console.log('Enter is pressed !');
  }
});
&lt;input id="inp"&gt;

【讨论】:

    【解决方案2】:

     &lt;td&gt; &lt;input type= "button" disabled id ="e2" value="Exercise 2" onclick ="loadQsets(2);setRadioValues(2);disableInput() ;" /&gt;&lt;/td&gt;

    window.onload=function(){
      var btn = document.getElementById('e2');
      
      function handleStuff() {
        loadQsets(2); 
        setRadioValues(2);
        disableInput();
      }
      
      btn.onclick = function() { 
        handleStuff();
      };
      
      btn.onkeydown = function() {
        handleStuff();
      }
    }
     &lt;td&gt; &lt;input type= "button" disabled id ="e2" value="Exercise 2" /&gt;&lt;/td&gt;

    【讨论】:

      猜你喜欢
      • 2013-01-22
      • 2015-07-15
      • 1970-01-01
      • 2020-01-18
      • 1970-01-01
      • 2021-09-27
      • 1970-01-01
      • 2017-04-25
      • 2016-02-22
      相关资源
      最近更新 更多