代码之家  ›  专栏  ›  技术社区  ›  user8839069

如何向动态生成的按钮添加文本?

  •  1
  • user8839069  · 技术社区  · 8 年前
     // Run loop through choices array
      for(let i = 0; i < choices.length; i++) {
        // Populate buttons to screen
        let choiceBtn = document.createElement("BUTTON");
        choiceBtn.classList.add("btn", "throws");
        choiceBtn.setAttribute("data-choice", choices[i]);
        infoScreen.appendChild(choiceBtn);
    

    我想我可以通过使用

    choiceBtn.innerHTML(choices[i]);
    

    但这似乎并不适用。innerText或appendChild,但我可能只是做了一些不正确的事情。我只是想问问你们。

    1 回复  |  直到 8 年前
        1
  •  0
  •   slevy1    8 年前

    而您可以使用按钮 .textContent innerText 属性(。 innerText 具有识别换行符的优点),最好是按照此方式显式创建新元素的文本节点 respondent 由于以下代码包含以下建议: 用户7393973 :

    var d = document;
    var choices = ["alpha", "beta", "gamma"];
    
    for (let i = 0; i < choices.length; i++) {
      let choiceBtn = d.createElement("BUTTON");
      choiceBtn.setAttribute("data-choice", choices[i]);
    
      /* recommended way: */
      choiceBtn.appendChild(d.createTextNode("Your\nChoice\nButton " + i));
      
      /* another way:
       choiceBtn.textContent = "Your\nChoice\nButton "+i;
      */
      /* and one more way:
       choiceBtn.innerText = "Your\nChoice\nButton "+i;
      */
    
      d.body.appendChild( choiceBtn );
    }
    button {
      width: 150px;
      height: 150px;
      color: #f00;
    }

    笔记这 resource 认为要么显式创建文本节点,要么使用。textContent属性在设置空元素的文本节点值方面同样合法。而且innerText最初是 MS extension to the DOM 在IE中,可以为文本节点设置和获取文本值。Google Chrome以同样的方式支持此功能。因此,总之,OP可以使用三种指示的方式之一设置文本节点。

    最后一点是:

    。。。无论何时使用innerHTML设置 无法控制的字符串。

    安全风险是XSS攻击的威胁;阅读更多信息 here