简体   繁体   中英

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. I have the popup.html file, which is what the user sees. 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:

<!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:

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!'. However, I then see a second call of the addEventListener, which then reverts back to the original popup.html form. 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? I realize that I really need to gain an understanding of the DOM model and how Javascript can interact with it in the browser. 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. 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.

Here is a skeleton outline of what I attempted:

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:

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. 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.

<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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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