简体   繁体   English

DOM元素在更新后立即消失

[英]DOM element disappearing immediately after update

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”,但是没有运气。

You are actually submitting the form. 您实际上是在提交表单。 Prevent that by adding return false to the onclick attribute: 通过将return false添加到onclick属性来防止这种情况:

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

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();
});

You are using input type="submit" inside Form tag , clicking this button will refresh the same page . 您在Form标记内使用输入type =“ submit”,单击此按钮将刷新同一页面。

try 尝试

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

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

or remove form tag 或删除表单标签

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

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