简体   繁体   English

javascript在事件监听器中更改html

[英]javascript change html in event listener

I'm starting to experiment with building Chrome extensions (first exposure to HTML and Javascript as well) and got stuck on a basic task. 我开始尝试构建Chrome扩展程序(也首次接触HTML和Javascript),并陷入了一项基本任务。 I have the popup.html file, which is what the user sees. 我有popup.html文件,这是用户看到的。 What I'd like to do is have some placeholder text that is initially displayed to the user. 我想做的是有一些占位符文本最初显示给用户。 The popup will also have a button so that when the user clicks on the button the placeholder text is replaced with something else. 弹出窗口还将具有一个按钮,以便当用户单击该按钮时,占位符文本将替换为其他内容。

Here is what I tested: 这是我测试的内容:

popup.html: popup.html:

<!doctype html>
<html>
  <head>
    <title>Test Extension</title>
    <script src="popup.js"></script>
  </head>
  <body>
      <form id="testForm">
          <input id="testButton" type="submit" value="testButton" />
      </form>
      <h3 id="textHeader">This will change.</h3>
  </body>
</html>

popup.js: popup.js:

function changeText() {
    document.getElementById('textHeader').innerHTML = 'Changed!';
}

document.addEventListener('DOMContentLoaded', function () {
  document.getElementById('testForm').addEventListener('submit', changeText);
});

When I debug the script, I see the initial addEventListener call which calls changeText and causes the text in the popup to change to 'Changed!'. 当我调试脚本时,我看到了初始的addEventListener调用,该调用调用changeText并使弹出窗口中的文本更改为“ Changed!”。 However, I then see a second call of the addEventListener, which then reverts back to the original popup.html form. 但是,我然后看到第二次调用addEventListener,然后将其恢复为原始的popup.html表单。 The net effect is that 'Changed!' 最终结果是“已更改!” only appears for a brief instant. 仅短暂出现。

Is there a way to make changes to the HTML file in an event listener permanent to get the intended behavior? 有没有一种方法可以永久更改事件侦听器中的HTML文件以获得预期的行为? I realize that I really need to gain an understanding of the DOM model and how Javascript can interact with it in the browser. 我意识到我确实需要了解DOM模型以及Javascript如何在浏览器中与之交互。 I'm looking for a book or some other resource to consult (the Mozilla Developer Network site looked like a good authoritative source, but seemed kind of sparse), but in the meantime was hoping to gain at least some additional understanding by working through this simple example. 我正在寻找一本书或其他参考资料(Mozilla开发人员网络站点看起来像是一个权威的资料,但是似乎很少),但是与此同时,希望通过此工作至少能获得一些额外的理解。简单的例子。 Thanks! 谢谢!


EDIT: 编辑:

Thank you everyone for the prompt responses! 谢谢大家的及时答复! Disabling the form submissions makes sense. 禁用表单提交是有意义的。 I'm adding this edit to my question post because the original task I was trying to achieve did in fact need to make use of a form. 我将此编辑添加到我的问题中,因为实际上我要实现的原始任务确实需要使用表单。

What I'm trying to do is take in input from the user through a form, query an external site (ex: Wikipedia) for the phrase that user typed in, and then display in the popup content that's taken from the query. 我要做的是通过表单从用户那里输入输入,查询外部站点(例如Wikipedia)以输入用户输入的短语,然后在从查询中获取的弹出内容中显示。

Here is a skeleton outline of what I attempted: 这是我尝试过的基本概述:

popup.html: popup.html:

<!doctype html>
<html>
    <head>
        <title>Test Extension</title>
        <script src="popup.js"></script>
    </head>

    <body>
        <form id="WikipediaForm">
            <input type="text" id="userQuery" size="50"/>
            <input id="submitQuery" type="submit" value="Ask Wikipedia" />
        </form>
        <h3 id="WikipediaResponse">placeholder</h3>
    </body>

</html>

popup.js: popup.js:

function changeText() {    
var req = new XMLHttpRequest();
askURL = 'http://en.wikipedia.org/wiki' + encodeURIComponent(document.getElementById('userQuery').value);
req.open("GET", askURL, false);

req.onload = function (e) {
    if (req.readyState === 4) {
        if (req.status === 200) {
                document.getElementById('WikipediaResponse').innerHTML = req.responseText; // i'm just dumping everything for now
            }
        } else {
            console.error(req.statusText);
        }
    }
};
req.send(null);
}

document.addEventListener('DOMContentLoaded', function () {
  document.getElementById('WikipediaForm').addEventListener('submit', changeText);
});

This again also faces the same issue that I saw with the previous example where the response flashes for an instant before reverting back to the placeholder text. 这又遇到了与上一个示例相同的问题,在该示例中,响应会闪烁一会儿,然后再返回到占位符文本。 However, I can't follow the earlier answers now because I need the form to be submitted. 但是,由于我需要提交表单,因此我现在无法遵循先前的答案。 What is the usual way of changing content in an event listener for a form? 在表单的事件侦听器中更改内容的常用方法是什么?

On another note, I'm using the synchronous XMLHttpRequest call, which I know isn't recommend. 另一方面,我正在使用同步XMLHttpRequest调用,我知道不建议这样做。 But when I used the asynchronous call it didn't seem to go through and I couldn't figure out how to fix that, so that's another problem I'm also working on. 但是,当我使用异步调用时,它似乎没有通过,而且我不知道如何解决该问题,所以这也是我正在研究的另一个问题。

Use: 采用:

function changeText() {
    document.getElementById('textHeader').innerHTML = 'Changed!';
    //Returning false will prevent that the form submission completes
    return false;
}

But if your form is never going to send data anywhere, you don't need a form at all (unless you're going to use a reset button for your fields). 但是,如果您的表单永远不会在任何地方发送数据,则根本不需要表单(除非您要对字段使用重置按钮)。 So you can just add type="button" to your element. 因此,您只需将type="button"添加到您的元素即可。

<body>
      <input id="testButton" type="button" value="testButton" />
      <h3 id="textHeader">This will change.</h3>
</body>

You need to return false from the event handler to prevent the normal form submission after the handler runs: 您需要从事件处理程序中返回false ,以防止在处理程序运行后正常提交表单:

function changeText() {
    document.getElementById('textHeader').innerHTML = 'Changed!';
    return false;
}

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

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