如何检查我的按钮是否在JavaScript中被单击?

时间:2019-05-09 13:50:11

标签: javascript html

我想在按Enter或单击按钮时调用JavaScript函数test(),但是我不知道如何检查在test()中是否单击了按钮。

HTML代码:

<input id="data" type="text" name="data" value="" onkeypress="test()" /> 
<button id="button" type="submit" onclick="test()">button</button>

JavaScript:

function test() {
    let data = document.getElementById("data") ;
    let button = document.getElementById("button") ;
    if(data.onkeypressed = this.event.which === 13 || /*need to check if button was clicked*/) {
         ...
         ...
         ...
}

如何在JavaScript中执行此操作?

3 个答案:

答案 0 :(得分:1)

您可以通过this来运行并检查tagName

function test(e) {
    let data = document.getElementById("data") ;
    let button = document.getElementById("button") ;
    if(data.onkeypressed = this.event.which === 13 || e.tagName === "BUTTON") {
      console.log("button")
    }
}
<input id="data" type="text" name="data" value="" onkeypress="test(this)" /> 
        <button id="button" type="submit" onclick="test(this)" >button</button>

答案 1 :(得分:1)

您可以将this传递到test()并在其中使用:

function test(el) {
  let enter = el.id === 'data' && this.event.which === 13;
  console.log(`Called by ${el.id}${enter ? ' and Enter was pressed' : ''}.`);
}
<input id="data" type="text" name="data" value="" onkeypress="test(this)" />
<button id="button" type="submit" onclick="test(this)">Button</button>

答案 2 :(得分:0)

为此使用按钮的onclick事件处理程序。每次单击该按钮时都会调用它:

编辑:您还可以使用输入的onkeydown事件查看在选择输入框时用户是否按Enter。

var data = document.getElementById("data") ;
var button = document.getElementById("button");
button.onclick = function() {
  console.log("clicked!");
  test();
  //do something
}

data.onkeydown = function(e) {
  if(e.keyCode == 13) {
    console.log("ENTER IS PRESSED!");
    this.blur(); //de-selects the textbox
  }
}


function test() {
    //do something
}
<input id="data" type="text" name="data" value="" /> 
        <button id="button" type="submit" >button</button>