简体   繁体   中英

Only update added javascript elements on second click

I have some Javascript code that gets values from an array that processes a http response from a server and adds buttons to a modal window. So the ids for the buttons come from the array. On second click everything is fine and my buttons are added to the modal window. But when I call the function the next time it adds the buttons again, but it should only update the buttons. How can I handle it that the function will only update the buttons on second and further clicks?

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);

You need to check if the button already exists before you add it in that case. Since you know the id of the button you're about to create, you can see if there's already a button with that id and just update it instead.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM