简体   繁体   English

第二次点击仅更新添加的javascript元素

[英]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. 我有一些Javascript代码,它们从一个数组获取值,该数组处理来自服务器的http响应并将按钮添加到模式窗口。 So the ids for the buttons come from the array. 因此,按钮的ID来自数组。 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. 由于您知道将要创建的按钮的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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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