appendChild method isn't working

时间:2015-07-28 15:48:54

标签: dom

I am trying to write some appendChild() method but I am stuck here. It seems working but not displaying the result. Not sure what I am missing:

            <%@ Page Language="C#" AutoEventWireup="true" CodeFile="appendChild().aspx.cs" Inherits="DomExample_appendChild__" %>

            <!DOCTYPE html>

            <html xmlns="http://www.w3.org/1999/xhtml">
            <head runat="server">
                <title></title>

            </head>
            <body>
                <form id="form1" runat="server">
                <div>
                <ul id="myList">
                    <li>Books</li>
                    <li>Pen</li>
                    <li>Paper</li>
                </ul>
                    <button onclick="myFunction()">Click here...</button>
                </div>
                </form>
               <script>
                   function myFunction() {
                       var x = document.createElement("Li");
                       var y = document.createTextNode("Pad");
                       x.appendChild(y);
                       document.getElementById("myList").appendChild(x);
                   }
               </script>
            </body>
            </html>

1 个答案:

答案 0 :(得分:1)

I am guessing that the script is running correctly, but the form is also being submitted right after and page refreshes to the initial state. Try this:

        <%@ Page Language="C#" AutoEventWireup="true" CodeFile="appendChild().aspx.cs" Inherits="DomExample_appendChild__" %>
        <!DOCTYPE html>

        <html xmlns="http://www.w3.org/1999/xhtml">
        <head runat="server">
            <title></title>

        </head>
        <body>
            <form id="form1" runat="server">
            <div>
            <ul id="myList">
                <li>Books</li>
                <li>Pen</li>
                <li>Paper</li>
            </ul>
                <button onclick="myFunction(event);">Click here...</button>
            </div>
            </form>
           <script>
               function myFunction(e) {
                   e.preventDefault();
                   var x = document.createElement("Li");
                   var y = document.createTextNode("Pad");
                   x.appendChild(y);
                   document.getElementById("myList").appendChild(x);
               }
           </script>
        </body>
        </html>

...or you can implicitly define button type as "button" rather than default "submit" type:

<button onclick="myFunction()" type="button">Click here...</button>