DOM插入的简单javascript错误

时间:2013-12-06 00:10:14

标签: javascript html html5 dom getelementbyid

我编写了这个简单的代码来将一个单词插入到列表中,但由于某种原因在Chrome中,我对DOM的更改大约出现了1/10秒,然后消失了。 Firefox中没有任何事情发生。

<html>
<head>

<script>
window.onload = init;
function init(){
    var button = document.getElementById("submit");
    button.onclick = changeDiv;
}
function changeDiv(){
    var textInput = document.getElementById("textInput");
    var userInput = textInput.value;
    alert("adding " + userInput);
    var li = document.createElement("li");
    li.innerHTML = userInput;
    var ul = document.getElementById("ul");
    ul.appendChild(li);
}

</script>
</head>
<body>
    <form id="form">
        <input id="textInput" type="text" placeholder="input text here">
        <input id="submit" type="submit">
    </form>
    <ul id="ul">
    </ul>
</body>
</html>

2 个答案:

答案 0 :(得分:2)

您没有取消提交按钮操作,因此页面正在提交表单。

function changeDiv (e) {
    if (!e)
         e = window.event;

        //IE9 & Other Browsers
        if (e.stopPropagation) {
            e.stopPropagation();
        }
        //IE8 and Lower
        else {
          e.cancelBubble = true;
        }

    ...

答案 1 :(得分:1)

提交表单并重新加载页面,更改

<input id="submit" type="submit">

<input id="submit" type="button">