简体   繁体   English

如何聆听HTML页面中的提交按钮

[英]How to listen to press submit button in HTML page

This script emits the text-entered after the user press the enter key. 用户按下enter键后,此脚本将发出text-enteredtext-entered What I need is to listen to click on the submit button in my HTML page. 我需要听的是单击HTML页面中的“ submit按钮。 This is the script: 这是脚本:

// 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);

The HTML is: 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>

Looks like you're using the Addon-On SDK which is a legacy technology. 看起来您正在使用旧版技术Addon-On SDK。 Mozilla reccomends migrating to WebExtensions. Mozilla建议迁移到WebExtensions。

However to answer your question: With jquery you could do something like 但是要回答您的问题:使用jquery可以做类似的事情

$('#myform').submit(function(e) {
    e.preventDefault(); // don't submit
    console.log('do something');
});

With pure javascript you could do something like 使用纯JavaScript,您可以执行以下操作

var form = document.getElementById('myform');
form.addEventListener('submit', function(e) {
    e.preventDefault(); // don't submit
    console.log('do something');
})

To listen to clicks in the submit button, simply, in the script, add an event listener to the submit button. 要监听“提交”按钮中的单击,只需在脚本中将事件侦听器添加到“提交”按钮中即可。 But first, add and id to the submit button in the HTML: 但首先,在HTML的“提交”按钮中添加和id:

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

In the script: 在脚本中:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM