Create a new <div> with .createElement()

时间秒杀一切 提交于 2019-12-23 05:08:21

问题


Hi I'm new to Javascript, having problem creating and adding a new to the DOM. (I want to do this with native javascript not jquery).

When I click the "Calculate" button, I very briefly see the Text flash on the screen and then disappear. Nothing added to the DOM.

Here is my JS script:

function makeResponseBox() {
    document.getElementById("calculate").onclick = function()
    {
        var responseBox = document.createElement("DIV"); //create <div>
        var para = document.createElement("P");//create <p>
        var text = document.createTextNode("Text");//
        para.appendChild(text);//append text to para
        var newDiv = responseBox.appendChild(para);// append <p> to <div> and assign to variable
        document.body.appendChild(newDiv);//append as child to <body>
    }

}//close function (makeResponseBox)

window.onload=makeResponseBox;

Here is my HTML:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Add Element to DOM</title>
    <script src="calculate.js"></script>
</head>
<body id="main">
<h1>Add Element to DOM</h1>


<form id ="form">

    <fieldset>

        <input type="submit" value="Calculate" id="calculate" />


    </fieldset><!-- close fieldset -->

</form><!-- close form -->

</body>
</html>

回答1:


It's because the form is submitted so the page is reloaded

You need to add a parameter to your listener , say function(e) and call e.preventDefault() at the beginning of the listener.

example:

document.getElementById("calculate").onclick = function(e)
{
    e.preventDefault();
    var responseBox = document.createElement("DIV"); //create <div>
    var para = document.createElement("P");//create <p>
    var text = document.createTextNode("Text");//
    para.appendChild(text);//append text to para
    var newDiv = responseBox.appendChild(para);// append <p> to <div> and assign to variable
    document.body.appendChild(newDiv);//append as child to <body>
}

Or you could also change the type of your button to remove the submit function

<input type="button" value="Calculate" id="calculate" />

But then your <form> become useless and you could remove it




回答2:


change your submit type to button which will avoid the reload

 <input type="submit" value="Calculate" id="calculate" />

to

<input type="button" value="Calculate" id="calculate" />

and if you want to submit the form handle it from js



来源:https://stackoverflow.com/questions/31320469/create-a-new-div-with-createelement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!