DOM element disappearing immediately after update

后端 未结 3 711
野性不改
野性不改 2020-12-10 09:26

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 th

相关标签:
3条回答
  • 2020-12-10 10:12

    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;"/>
    
    0 讨论(0)
  • 2020-12-10 10:21

    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 讨论(0)
  • 2020-12-10 10:27

    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();
    });
    
    0 讨论(0)
提交回复
热议问题