简体   繁体   English

每次点击如何在js中动态添加字体真棒图标

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

I have a button that creates two new inputs fields each time the user clicks on a button.我有一个按钮,每次用户单击按钮时都会创建两个新的输入字段。 I want to create a font awesome icon next to the inputs each time the user clicks on the button.每次用户单击按钮时,我想在输入旁边创建一个很棒的字体图标。 It works currently but it creates an icon just once and I want to add an icon for each time the two fields are generated.它目前有效,但它只创建一次图标,我想在每次生成两个字段时添加一个图标。 How can I achieve this?我怎样才能做到这一点? Here is my attempt:这是我的尝试:

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

The reason you're only seeing one icon is that on every click you re-set secondContainer 's HTML, instead of adding to it.您只看到一个图标的原因是每次单击时都会重新设置secondContainer的 HTML,而不是添加到它。 Try changing this line:尝试更改此行:

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

Into this line:进入这一行:

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

Or, alternatively,或者,或者,

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

Please note, that while the above will work, you could also define an <i /> element just liek you did with the inputs, and append the element to secondContainer .请注意,虽然上述方法可行,但您也可以定义一个<i />元素,就像您对输入所做的那样,并将 append 元素定义为secondContainer

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

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