每次提交表单时都会触发DOMContentLoaded

时间:2017-07-02 22:33:40

标签: javascript google-chrome google-chrome-extension

我正在撰写Chrome扩展程序,其格式非常简单。

<html>
  <head>
    <title>Getting Started Extension's Popup</title>
    <script src="popup.js"></script> 
  </head>
  <body>
    <div id="status"></div>
    <form id="typeForm">
        Type: <input id="typeInput" type="text" name="type"><br>
        <input type="submit" value="Submit">
    </form>
  </body>
</html>

popup.js有以下内容:

document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('status').textContent = 'Enter Type';
    document.getElementById('typeForm').removeEventListener('submit', typeFormDidSubmit);
    document.getElementById('typeForm').addEventListener('submit', typeFormDidSubmit);
});

function typeFormDidSubmit() {
    var type = document.getElementById('typeInput').textContent;
    if (type && type.length > 0) {
        document.getElementById('status').textContent = 'Processing...';
        startProcessing();
    } else {
        document.getElementById('status').textContent = 'Type cannot be empty';
    }
}

现在的问题是,无论我在表单中输入什么,无论是空还是其他字符,只要调用typeFormDidSubmit,DOMContentLoaded也会被触发,将状态消息闪回“Enter Type”。我认为DOMContentLoaded每页只调用一次。

在页面加载时,我只能调用第一组命令吗?

1 个答案:

答案 0 :(得分:0)

在阅读@Jaromanda X的评论并阅读提交表单后,似乎该表单用于POST请求和一些数据。 由于我想调用本地JS函数,我应该使用TextArea + Button。

相关问题