考虑以下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.
为什么会出现此错误?如何解决这个问题?
答案 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 强>