簡體   English   中英

每次點擊如何在js中動態添加字體真棒圖標

[英]How to add font awesome icon dynamically in js every click

我有一個按鈕,每次用戶單擊按鈕時都會創建兩個新的輸入字段。 每次用戶單擊按鈕時,我想在輸入旁邊創建一個很棒的字體圖標。 它目前有效,但它只創建一次圖標,我想在每次生成兩個字段時添加一個圖標。 我怎樣才能做到這一點? 這是我的嘗試:

   createNewPricedRoundShareholder() {
      var newPlatformNameInputContainer = document.getElementById(
        "round-shareholder-container"
      );

      const newPlatformNameInput = document.createElement("input");
      newPlatformNameInput.classList.add("form-control");
      newPlatformNameInput.classList.add("input");
      newPlatformNameInput.placeholder = "Username";
      newPlatformNameInput.setAttribute("type", "text");
      newPlatformNameInput.setAttribute("name", "username");

      newPlatformNameInputContainer.appendChild(newPlatformNameInput);

      var secondContainer = document.getElementById(
        "round-investment-container"
      );

      const newInitialOptionsPool = document.createElement("input");
      newInitialOptionsPool.classList.add("form-control");
      newInitialOptionsPool.classList.add("input");
      newInitialOptionsPool.placeholder = "Investment";
      newInitialOptionsPool.name = "investment";
      newInitialOptionsPool.setAttribute("type", "text");
      newInitialOptionsPool.setAttribute("name", "investment");
      secondContainer.appendChild(newInitialOptionsPool);
      secondContainer.innerHTML = '<i class="fas fa-trash"></i>';
    }

您只看到一個圖標的原因是每次單擊時都會重新設置secondContainer的 HTML,而不是添加到它。 嘗試更改此行:

secondContainer.innerHTML = '<i class="fas fa-trash"></i>';

進入這一行:

secondContainer.innerHTML = secondContainer.innerHTML + '<i class="fas fa-trash"></i>';

或者,或者,

secondContainer.innerHTML += '<i class="fas fa-trash"></i>';

請注意,雖然上述方法可行,但您也可以定義一個<i />元素,就像您對輸入所做的那樣,並將 append 元素定義為secondContainer

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM