2016-07-31 4 views
0

サーバからのHTTPレスポンスを処理し、モーダルウィンドウにボタンを追加する配列から値を取得するJavaScriptコードがあります。したがって、ボタンのIDは配列から取得されます。 2回目のクリックですべてが問題なく、私のボタンがモーダルウィンドウに追加されます。しかし、次回にボタンを追加するときに関数を呼び出すと、ボタンが更新されるだけです。 この関数は、2回目以降のクリックでのみボタンを更新することはできますか?2回目のクリックで追加された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

ありがとうございましたが、もう一度機能を読み込むと、ボタンが再び追加されます。私が望むのは、すべてのボタンが2度目に追加されるわけではないが、ボタンは更新されるべきであり、それぞれが1回だけ存在することである。簡単な方法でこれを行う可能性はありますか? @ kamoroso94 – Tmyr

+0

私はあなたの問題の詳細のいくつかにあいまいかもしれないと思います。 JSFiddleのサンプルを作って、あなたが探しているものを示しています。そうでない場合は、質問をさらに詳細に更新できますか? https://jsfiddle.net/x5k57o01/ – kamoroso94

+0

これはあなたが持っている問題についてもっと詳しく教えてくれません。あなたはボタンが重複し続けると述べました。このコードをいつ呼び出すのですか?また、あなたは 'resultContainers'と' resultContainerValues'変数の値をどこで取得していますか? – kamoroso94

関連する問題