如何在列表的每一行之后创建按钮?

How to create buttons after each line of the list?

我想显示一个球员的技能和价值列表,并在每行之后创建一个递增和递减按钮来增加或减少价值。我试图从与此问题相关的其他问题中收集线索,但我是初学者,无法解决。 这是我的代码:

var text = "<ul>";
var i = 0;

for (i; i < this.skillPoints.length; i++) {
  text +=
    "<li>" +
    this.skillPoints[i]._name +
    " value is: " +
    this.skillPoints[i]._value +
    "</li></br>";

    var entry = document.createElement('li');
    entry.appendChild(document.createTextNode(text));

    var btn = document.createElement("BUTTON");
    btn.innerHTML = "Increment";
    entry.appendChild(btn);
}

text += "</ul>";
document.getElementById("list").innerHTML = text;

您混淆了很多可以单独工作的功能。要么决定将文本添加为​​ innerHTML,要么将元素添加为 appendChild(document.createElement(x))。此外 createTextNode() 会创建 HTML 编码输出,而不是您想要的。最后,你应该等到DOM输出完成后才全部添加。

这是一个尽可能接近您的代码的更正示例。

//REM: For testing
var skillPoints = [
 {_name: 'Skill 1', _value: 'a'},
 {_name: 'Skill 2', _value: 'b'}
];

//REM: Start of the list
var text = "<ul>";

//REM: Removed "this" for testing purposes
for(var i=0; i < skillPoints.length; i++){
  text += "<li>";
  text += skillPoints[i]._name;
  text += " value is: ";
  text += skillPoints[i]._value;
  text += "</li></br>";
  text += "<button> Increment </button>";

  //REM: Not required.. the li gets added as string already in this case. Use either or but not both.
  //var entry = document.createElement('li');

  //REM: First, textnode adds encoded HTML and second, the list is not complete yet
  //REM: https://developer.mozilla.org/en-US/docs/Web/API/Document/createTextNode
  //entry.appendChild(document.createTextNode(text));
};

text += "</ul>";

//REM: Now that the ul is complete, we add it to the DOM
//REM: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
document.body.insertAdjacentHTML('beforeend', text);