2016-07-31 46 views
0

我有一些Javascript代碼從一個處理來自服務器的http響應的數組中獲取值,並將按鈕添加到模式窗口。所以按鈕的ID來自陣列。 第二次點擊一切都很好,我的按鈕被添加到模態窗口。但是當我在下次再次添加按鈕時調用該函數時,它應該只更新按鈕。 我該如何處理該功能只會更新第二次和更多次點擊的按鈕?僅第二次點擊更新添加javascript元素

buttonContainer = document.getElementById('modal1');     
     for (i = 0; i < resultContainers.length; i++) { 
      newButton = document.createElement('input'); 
      newButton.type = 'button'; 
      newButton.value = resultContainers[i]; 
      newButton.id = resultContainerValues[i]; 
      newButton.class = 'buttonContainer'; 
       if (newButton.id == 'true') { 
        newButton.style.backgroundColor = '#8cff1a'; 
       }; 
      newButton.onclick = function() { 
       alert('You pressed '+this.id); 
      }; 
      buttonContainer.appendChild(newButton); 

回答

0

在這種情況下,您需要檢查按鈕是否已經存在,然後再添加它。既然你知道你要創建的按鈕的ID,你可以看看是否已經有一個具有該ID的按鈕,而只是更新它。

var newButton = document.getElementById(resultContainerValues[i]); 
if(newButton!=null) { 
    newButton.value = resultContainers[i]; 
} else { 
    newButton = document.createElement('input'); 
    newButton.type = 'button'; 
    newButton.value = resultContainers[i]; 
    newButton.id = resultContainerValues[i]; 
    newButton.class = 'buttonContainer'; 
    if (newButton.id == 'true') { 
     newButton.style.backgroundColor = '#8cff1a'; 
    } 
    newButton.onclick = function() { 
     alert('You pressed '+this.id); 
    }; 
    buttonContainer.appendChild(newButton); 
} 
+0

謝謝你的幫助,但是當我第二次加載函數時,按鈕將被重新添加。我想要的是,並非所有的按鈕都會再次添加,但按鈕應該更新,每個按鈕只存在一次。有沒有可能以簡單的方式做到這一點? @ kamoroso94 – Tmyr

+0

我想我可能對你的問題的一些細節模糊不清。我做了一個JSFiddle示例,它顯示了我希望你在尋找的東西。如果沒有,也許你可以用更多的細節更新你的問題? https://jsfiddle.net/x5k57o01/ – kamoroso94

+0

這真的沒有告訴我更多關於你遇到的問題。你提到按鈕不斷重複。你什麼時候調用這段代碼,你在哪裏得到'resultContainers'和'resultContainerValues'變量的值? – kamoroso94

相關問題