getElementById(element).innerHTML缓存? [英] getElementById(element).innerHTML cache?

查看:127
本文介绍了getElementById(element).innerHTML缓存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的页面代码:

<!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>

我很困惑,为什么当我按添加1按钮输入一些文字,然后再次按添加1按钮,我刚刚输入的文字消失!

I am very confused as to why when I press the "Add 1" button enter some text and then press the "Add 1" button again the text that I just entered disappears!

如果有人可以给出一些洞察力,那将是非常感谢的。 $ b

If anyone could give some insight to this it would be greatly appreciated

推荐答案

您的其他值消失的原因是因为当您执行 something.innerHTML + = something 将重写该区域的HTML(意味着之前的内容已经消失,并将被新的新HTML替代)。你可能想做的是这样的:

The reason your other values disappear is because when you do something.innerHTML += something it will rewrite the HTML for that zone (meaning what was there before is gone and will be replaced with fresh new HTML). What you probably want to do is something along this :

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中的其他元素

Using appendChild won't alter the other element that are already in the div namevalues.

这篇关于getElementById(element).innerHTML缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆