有没有办法循环使用单选按钮的innerText?我有一个数组中的值,我想将它们作为文本循环到我正在循环的单选按钮。我有一个for-llop,它创建了带有类和值的单选按钮,现在我需要将值用作文本跟着它。像这样:
<input type="radio" class="response" value="2">2
我到目前为止的代码是:
let radioButtons = Object.values(questionAlternatives)
for (let i = 0; i < Object.keys(questionAlternatives).length; i++) {
let answerRadio = document.querySelector('#answerRadio')
let radioButton = document.createElement('input')
radioButton.setAttribute('type', 'radio')
radioButton.setAttribute('class', 'response')
radioButton.setAttribute('value', radioButtons[i])
answerRadio.appendChild(radioButton)
}
任何方式都可行吗?
答案 0 :(得分:0)
经过一番挖掘后我找到了答案:
for (let i = 0; i < Object.keys(questionAlternatives).length; i++) {
let answerRadio = document.querySelector('#answerRadio')
let radioButton = document.createElement('input')
let radioText = document.createTextNode(radioButtons[i].toString())
radioButton.setAttribute('type', 'radio')
radioButton.setAttribute('class', 'response')
radioButton.setAttribute('value', radioButtons[i])
answerRadio.appendChild(radioButton)
answerRadio.appendChild(radioText)
}