简体   繁体   中英

Javascript: Dynamically created button disappears?

I am new to Javascript. I want to dynamically create a new button when a user clicks on the "Create Element" button. The script creates a button but only for a fraction of second. Also the 'value' attribute is not set for the button.

If there is any theory behind the behavior please redirect me to the proper URL.

Here is the code :

<html>

<head>
    <script type="text/javascript">
    function doSomething(){     
        myButton = document.createElement("button");        
        myButton.setAttribute("value","New Button");        
        document.getElementById("myForm").appendChild(myButton);        
    }
    </script>
</head>

<body>
    <form id="myForm">
        <button name="myButton" id="myButtonID" onclick="doSomething()">Create Element</button>
    </form>
</body>

</html>

A <button> element is a submit button by default - thus you're submitting the form, causing a reload of the page.

You'd need to use:

<button type="button" ...>...</button>

Or:

<input type="button" ...>

您的onclick回调必须返回false。

<button name="myButton" id="myButtonID" onclick="doSomething(); return false">

i would not create the button that way. I would do something like this:

    myButton = document.createElement('input');
myButton.setAttribute("type","button");

As already mentioned before use "input" instead "button". Because "button" cause a postback with page refresh. By using "input" you won't get the postback

// create new element in html page

function createElement_Click()
{

    // btn variable will contain a RAW html [<input></input>] object
    var btn = document.createElement("input");
    //So now we can manipulate its properties:
    btn.type = "button"; //equal to (<input type="button"></input>) in html

    //add some value to it
    btn.value = "Click Me";
    btn.id = "btnShow";
    btn.onclick = function() { ShowMessage(); };

    // step -1 put your newly created object into html
    document.getElementById("myDiv").appendChild(btn);


}

function ShowMessage() {
    alert("hello world");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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