我想在表单<form>里面添加新的DOM元素。 使用appendChild()来添加。可是appendChild()在<form>里面就是用不了。但是把appendChild放到<form>外面,立马就可以用了。
请问有什么办法可以让appendChild()在表单里面使用的吗?<!DOCTYPE html>
<html>
<body><form>
<ul id="myList"><li>Coffee</li><li>Tea</li></ul>
<p id="demo">Click the button to append an item to the list</p>
<button onclick="myFunction()">Try it</button>
</form><script>
function myFunction()
{
var node=document.createElement("LI");
var textnode=document.createTextNode("Water");
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);
}
</script><p><strong>Note:</strong><br>First create an LI node,<br> then create a Text node,<br> then append the Text node to the LI node.<br>Finally append the LI node to the list.</p></body>
</html>
HTMLDOMjavascript

解决方案 »

  1.   

    <form onsubmit="return false;">不知道怎么回事,表单提交了,页面刷新了,所以没有看到效果。
      

  2.   

    button在xhtml申明或者w3c浏览器下等价于type='submit',所以提交了表单button在IE下的表现形式
      

  3.   

    其实是有用的,只是点了以后form又提交了而已。阻止一下事件冒泡跟button的默认行为即可,代码如下:<!DOCTYPE html>
    <html>
    <body><form>
    <ul id="myList"><li>Coffee</li><li>Tea</li></ul>
    <p id="demo">Click the button to append an item to the list</p>
    <button onclick="myFunction(event)">Try it</button>
    </form><script type="text/javascript">
    function myFunction(e){//添加一个参数,这个参数为点击事件的event
    if(e.preventDefault){
        e.preventDefault();//FF等阻止DOM节点默认行为,这里是提交表单的行为
        e.stopPropagation();
    }else{
        e.cancelBubble = true;//FF等阻止事件冒泡
        e.returnValue = false;//IE阻止DOM节点默认行为,这里是提交表单的行为
    }
    var node=document.createElement("LI");
    var textnode=document.createTextNode("Water");
    node.appendChild(textnode);
    document.getElementById("myList").appendChild(node);
    }
    </script><p><strong>Note:</strong><br>First create an LI node,<br> then create a Text node,<br> then append the Text node to the LI node.<br>Finally append the LI node to the list.</p></body>
    </html>
      

  4.   

    if(e.preventDefault){
        e.preventDefault();//FF等阻止DOM节点默认行为,这里是提交表单的行为
        e.stopPropagation();//FF等阻止事件冒泡
    }else{
        e.cancelBubble = true;//IE阻止事件冒泡
        e.returnValue = false;//IE阻止DOM节点默认行为,这里是提交表单的行为
    }
    注释弄错了,剪切了没改。。
      

  5.   

    你的节点是成功了的,但是因为你的按钮把form给提交了,所以又重新刷新了.你可以改成
    <button onclick="myFunction()" type="button">Try it</button>