最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - DOM element disappearing immediately after update - Stack Overflow

programmeradmin6浏览0评论

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.

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

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

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.

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

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

Share Improve this question edited Jan 21, 2014 at 16:19 kassold asked Jan 21, 2014 at 16:13 kassoldkassold 4693 gold badges9 silver badges21 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 14

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

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

<form onsubmit="return false;">

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

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

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 .

try

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

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

or remove form tag

发布评论

评论列表(0)

  1. 暂无评论