简体   繁体   中英

Why does this HTML/JS revert back to the original after changing the inner HTML?

I am starting to learn JavaScript and I was wondering why this doesn't permanently make "Ephemeral" appear before the button and why it reverts back to the original HTML page before the button is pressed?

index.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="mind.js"></script>
</head>
<body>
    <h1 id = "identifier"></h1>
    <form>
        <button value = "button!" onclick="doSomething()"> </button>
    </form>
</body>
</html>

mind.js

function doSomething() {
    document.getElementById("identifier").innerHTML = '<i>Ephemeral</i>';
}

Because you're submitting the form, which is refreshing the page. Add return false to the inline handler, if you don't want to submit yet.

<button value = "button!" onclick="doSomething(); return false;"> </button>

Or add return before the call, and add return false to the function.

<button value = "button!" onclick="return doSomething();"> </button>

function doSomething() {
    document.getElementById("identifier").innerHTML = '<i>Ephemeral</i>';
    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