2013-01-17 68 views
0

我有一個圖像和名稱顯示在一個新的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'; 
+0

Unbelieveable。我曾嘗試過,但不能刷新或什麼。將允許時接受。謝謝。 – Inkers

回答

2

刪除var htmlStr="";並在每次迭代循環中聲明它。因此,改變

htmlStr += theName; 

var htmlStr = theName; 

,這應該解決您的問題

+1

你可以保留'var htmlStr =「」;'它在哪裏,只需將第二行改爲'htmlStr = theName;'。移動'var'不會改變範圍。真正的問題是'+ ='。 – gpojd

+0

@gpojd你是對的,我認爲如果你把這個聲明放在循環中,它會變得更容易 - 它顯示變量是爲了循環的目的而創建的...我想它的個人偏好 – ManseUK