javascript DOM 元素在更新后立即消失

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21263414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 20:30:14  来源:igfitidea点击:

DOM element disappearing immediately after update

javascripthtml

提问by kassold

I have the following javascript function that updates a text within a div when a button is clicked (using an onclick() event) It works, but it immediately changes back to the old text.

我有以下 javascript 函数,可以在单击按钮时更新 div 中的文本(使用 onclick() 事件)它可以工作,但它会立即变回旧文本。

function func()
{
    var text = document.getElementById("text");
    text.innerHTML = "Changed";
};

The HTML

HTML

<body>
    <form>
        <input type="submit" value="Add Text" onclick="func()"/>
    </form>
    <div id="text">
        Text to Change
    </div>
</body>

What am I missing? I also tried returning 'false' from the function but no luck.

我错过了什么?我也尝试从函数中返回“false”,但没有成功。

回答by wanten

You are actually submitting the form. Prevent that by adding return false to the onclick attribute:

您实际上是在提交表单。通过向 onclick 属性添加 return false 来防止这种情况:

<input type="submit" value="Add Text" onclick="func(); return false;"/>

回答by Benjamin Gruenbaum

The form submits causing the page to refresh and reload the original content.

表单提交导致页面刷新并重新加载原始内容。

Try returning false on a form submit handler to prevent the default action:

尝试在表单提交处理程序上返回 false 以防止默认操作:

<form onsubmit="return false;">

If I may suggest, avoid inline event handlers altogether. Instead use the modern events API with the much nicer addEventListener:

如果我可以建议,请完全避免使用内联事件处理程序。而是使用具有更好的现代事件 API addEventListener

<body>
    <form id='mainForm'>
        <input type="submit" value="Add Text"/>
    </form>
    <div id="text">
        Text to Change
    </div>
</body>

Javascript:

Javascript:

var form = document.getElementById("mainForm");
var text = document.getElementById("text"); // probably not a very good id!
form.addEventListener("submit",function(e){ 
    text.innerHTML = "Hello!";
    e.preventDefault();
});

回答by Piyush

You are using input type="submit" inside Form tag , clicking this button will refresh the same page .

您在 Form 标签中使用 input type="submit" ,单击此按钮将刷新同一页面。

try

尝试

    <input type="button" value="Add Text" onclick="func()"/>

<div id="text">
    Text to Change
</div>

or remove form tag

或删除表单标签