我在新的 div 中显示了图像和名称。但是,我遇到了一个问题,下次有人输入姓名和图片并按“保存”时,他们的 userDiv 显示他们的姓名加上以前的用户名。例如,有两个用户:用户 1 和用户 2。当我选择所有用户并循环遍历结果时,名称的记录方式不同。用户 1 显示为“用户 1”,但用户 2 显示为“用户 1 用户 2”。快速浏览一下,我认为这是因为innerHTML 从父div 获取所有内容,但我不确定。
var htmlStr="";
var theID;
var theName;
var thePhoto;
var len = results.rows.length;
console.log(len);
for(var i = 0; i < len; i++){
theID = results.rows.item(i).id;
console.log(theID);
theName = results.rows.item(i).username;
htmlStr += theName;
console.log(theName);
thePhoto = results.rows.item(i).imagepath;
console.log(thePhoto);
var imageHold= new Image();
imageHold.src = thePhoto;
console.log("this is the src:"+imageHold.src);
var userDiv = document.createElement("div");//Create the div
userDiv.innerHTML=htmlStr;
userDiv.appendChild(imageHold);
document.getElementById('showUsers').appendChild(userDiv);//append it to the document
userDiv.style.display = 'block';
最佳答案
删除 var htmlStr="";
并在每次迭代的循环中声明它。所以改变一下
htmlStr += theName;
到
var htmlStr = theName;
这应该可以解决您的问题
关于javascript - 为什么结果在循环中显示结果加上先前的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14381185/