这是我的页面代码:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Marketing Tracking</title>
</head>
<body>
<form action="#" id="form" method="post">
<div id="namevalues">
<span id="span:1">
<input type="text" id="name:1" onchange="changed(this)" style="width:300px;"/>
<input id="value:1" type="number" min="0" value="0" /><br /></span>
</div>
<input type="button" id="add" value="Add 1" />
<br />
<textarea name="talk" style="width:500px;height:175px;"></textarea>
<br />
<input type="button" id="update" value="Update"/>
</form>
<script>
function get(a){return document.getElementById(a);}
up=get("update");
up.onclick = function(){
get("form").submit();
}
get("name:1").onchange = function(){changed(this)};
get("add").onclick = function(){add()};<% z=2 %>
function changed(ele){
id=ele.id;
val=ele.value;
id=id.split(":")[1];
get("value:"+id).name=get("name:"+id).value;
}
function add(){
document.getElementById("namevalues").innerHTML+='<span id="span:'+z+'"><input type="text" id="name:'+z+'" onchange="changed(this)" style="width:300px;"/><input id="value:'+z+'" type="number" min="0" value="0" /><br /></span>';
}
</script>
</body>
</html>
我很困惑为什么当我按下 Add 1 按钮输入一些文本然后再次按下 Add 1 按钮时,我刚刚输入的文本消失了!
如果有人能对此提供一些见解,我们将不胜感激。
最佳答案
您的其他值消失的原因是因为当您执行 something.innerHTML += something
时,它将重写该区域的 HTML(这意味着之前的内容已经消失,并将被新的替换) HTML)。您可能想要做的是:
function add(){
var div = document.createElement("div");
div.innerHTML = '<span id="span [... the rest of the code ...]<br /></span>';
document.getElementById("namevalues").appendChild(div);
}
使用 appendChild
不会改变已经在 div namevalues
中的其他元素。
关于javascript - getElementById(element).innerHTML 缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11068421/