为什么这个 HTML/JS 在更改内部 HTML 后会恢复到原始状态

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

本文关键字:HTML 恢复 原始 状态 原始状 内部 JS 为什么      更新时间:2023-09-26

我开始学习JavaScript,我想知道为什么这不会永久地使"短暂"出现在按钮之前,为什么它会在按下按钮之前恢复到原始HTML页面?

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

心.js

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

因为您正在提交表单,这会刷新页面。如果还不想提交,请将return false添加到内联处理程序。

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

或者在调用之前添加return,并向函数添加return false

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

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