第二个按钮单击生成异常

时间:2013-12-13 16:38:46

标签: javascript html

考虑以下HTML

<div id="parent" class="parent">
    <div id="child" class="child">
        <input type="text" class="text"/>
        <input id="submit" value="submit" type="submit" onclick="doThis()"/>
    </div>
<div>

JS代码

function doThis(){
    var span= document.createElement("span");
    var parent=document.getElementById("parent");
    var child=document.getElementById("child");
    var submit=document.getElementById("submit");
    child.insertBefore(span,submit);
    myKeys=[];
    myKeys.push(getAllKeyValuePair(submit));
    span.innerHTML=myKeys;
}
function getAllKeyValuePair(obj){
    var str="";
    for(var key in obj){
        try{
            str=str+"{"+key+", "+obj[key]+"}";
        }
        catch(e){
            console.log(key);
        }
    }
    return str;
}

JSFIDDLE 即可。再次点击submit按钮,生成以下错误Uncaught NotFoundError: An attempt was made to reference a Node in a context where it does not exist.为什么会出现此错误?如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

通过innerHTML插入函数getAllKeyValuePair()创建的数据,您还复制以下代码

...}{outerHTML,
<input id="submit" type="submit" onclick="doThis()" value="submit">
}{...

这是由javascript引导的另一个元素,ID为“submit”复制标识符,当你再次尝试执行时导致错误

 var submit=document.getElementById("submit");
    child.insertBefore(span,submit);

答案 1 :(得分:1)

您的第span.innerHTML=myKeys;行导致了该问题,因为它导致页面上的提交按钮元素重复。只需将span.innerHTML=myKeys;更改为span.textContent = myKeys;即可正常使用。

<强> jsFiddle example