我正在做一个小项目,我有一个包含4个数字的数组。我想在4个按钮上显示它们。我尝试了这段代码,但似乎没有用。你有什么想法我可能会犯错误吗?
<div id="results">
<button type="button" class="btn btn-primary button-result" id="button1">Result</button>
<button type="button" class="btn btn-primary button-result" id="button2">Result</button>
<button type="button" class="btn btn-primary button-result" id="button3">Result</button>
<button type="button" class="btn btn-primary button-result" id="button4">Result</button>
</div>
var rnum1 = generateRandomNumber1();
var rnum2 = generateRandomNumber2();
var rnums = [rnum1, rnum2];
var rnumsSort = rnums.sort(function(a, b) {
return b - a
});
//pass the random numbers to the function
var data = generateRandomOperatorAndCorrectResult(rnumsSort[0], rnumsSort[1]);
//data=["+", [5]]
var operator = data[0];
var corResult = data[1][0][0];
var ranResult = [data[1][0][1], data[1][0][2], data[1][0][3]];
var allResults = data[1][0];
var sortAllResults = allResults.sort(function(a, b) {
return a - b
});
var buttonText = buttonResult();
function buttonResult() {
for (var i = 0; i < sortAllResults.length; i++) {
document.querySelectorAll(".button-result").textContent = sortAllResults[i];
}
}
答案 0 :(得分:0)
您正在尝试在此行中设置NodeList的textContent
:
document.querySelectorAll(".button-result").textContent= sortAllResults[i];
您需要选择当前按钮的索引:
document.querySelectorAll(".button-result")[i].textContent= sortAllResults[i];
答案 1 :(得分:0)
只是一个小示例,说明如何填充按钮。
const randomNumber = Math.floor(1000 + Math.random() * 9000);
[...myArray] = randomNumber.toString();
const insertResult = (origArray) => {
const myButtons = Array.from(document.getElementsByClassName('button-result'));
origArray.sort((a, b) => b - a);
myButtons.forEach((button, index) => button.textContent = myArray[index]);
};
insertResult(myArray);
<div id="results">
<button type="button" class="btn btn-primary button-result" id="button1">Result</button>
<button type="button" class="btn btn-primary button-result" id="button2">Result</button>
<button type="button" class="btn btn-primary button-result" id="button3">Result</button>
<button type="button" class="btn btn-primary button-result" id="button4">Result</button>
</div>