如何在HTML页面中收听按提交按钮

时间:2017-05-07 19:37:07

标签: javascript javascript-events firefox-addon firefox-addon-sdk

用户按下text-entered键后,此脚本会发出enter。我需要的是听取我的HTML页面中的submit按钮。这是脚本:

// When the user hits return, send the "text-entered"
// message to main.js.
// The message payload is the contents of the edit box.
var textArea = document.getElementById("txt-field");
textArea.addEventListener('keyup', function onkeyup(event) {
  if (event.keyCode == 13) {
    // Remove the newline.
    text = textArea.value.replace(/(\r\n|\n|\r)/gm,"");
    addon.port.emit("text-entered", text);
    textArea.value = '';
  }
}, false);

HTML是:

<html>
<head>
    <style type="text/css" media="all">
      textarea {
        margin: 10px;
      }
      body {

        background-color:#b3dbfa;
      }
    </style>
  </head>

  <body>

  <form> 
      Enter URL: <br>
      <input type="text" id="txt-field">
      <input type="submit" value="Add">
  </form>
  <script src="get-text.js"></script>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

要在提交按钮中收听点击,只需在脚本中向提交按钮添加事件监听器即可。但首先,在HTML中的提交按钮中添加和id:

<input type="submit" value="Add" id="submit-btn">

在剧本中:

addbtn=document.getElementById("submit-btn");
addbtn.addEventListener('click', function (event) {
event.preventDefault();
// Get the text and remove the newline.
var text = formTextArea.value.replace(/\s/,"");    //remove space characters
var level = document.getElementById("levels-list").value;
//send the entered data to the addon to store them
self.port.emit("text-entered", text);
                                                        self.port.emit("selected-level", level);
formTextArea.value = ''; //intialise the text area to empty after adding the item.
}
,false);