HTML单选按钮标签 - 填写Javascript ID?

时间:2017-01-19 09:55:12

标签: javascript html

我有这个HTML -

 <div class="qa">
<div class="questions"></div>
<div class="answers">
  <div class="answer">
    <input type="radio" name="answer" value="Correct" id="Correct" /><label for="Correct"> Answer 1 </label>
  </div>
  <div class="answer">
    <input type="radio" name="answer" value="Incorrect" id="Incorrect" /><label for="Incorrect"> Answer 2 </label>
  </div>
</div>

我的JavaScript看起来像这样 -

var questions = [ {
"q": "When was Project Launched?",
"a": {"Correct": "That's Right!","Incorrect": "Nope, Project was launched in 2016"  },
"Option1": "2016",
"Option2": "2017"  
}, 

我想要的是动态拉动到HTML中的单选按钮标签的答案。所以我真的需要能够把#34; Option1&#34;和&#34;选项2&#34; ID进入<label for="Correct">空间而不仅仅是静态&#34; Answer1&#34; &#34; ANSWER2&#34;文本。

有可能吗?

谢谢,

2 个答案:

答案 0 :(得分:3)

尝试$('label[for=Correct]').html('New Label');或不使用Jquery

var input = document.getElementById('Correct');
var label = input.getElementsByTagName('label')[0];
label.innerHTML = 'New Text';

来自this answer

答案 1 :(得分:0)

这对你有帮助吗?

var questions = [ {
    "q": "When was Project Launched?",
    "a": {"Correct": "That's Right!","Incorrect": "Nope, Project was launched in 2016"  },
    "Option1": "2016",
    "Option2": "2017"  
}];



var divElement1 = document.getElementsByClassName("answer")[0];
divElement1.childNodes[3].innerText = questions[0].Option1;

var divElement2 = document.getElementsByClassName("answer")[1];
divElement2.childNodes[3].innerText = questions[0].Option2;
<div class="qa">
    <div class="questions"></div>
    <div class="answers">
        <div class="answer">
			<input type="radio" name="answer" value="Correct" id="Correct" />
			<label for="Correct"> Answer 1 </label>
		</div>
		<div class="answer">
			<input type="radio" name="answer" value="Incorrect" id="Incorrect" />
			<label for="Incorrect"> Answer 2 </label>
		</div>
	</div>
</div>