【发布时间】:2018-05-23 19:28:17
【问题描述】:
我正在尝试在 JS 中创建一个简单的测试。我有一个创建 4 个单选按钮并将它们添加到 html 的函数。当我调用它n 次时,我只需将相同的 4 个单选按钮添加到 div 并且当我尝试从第 4 个问题中选择一个答案时,它仍然会从第一个 div/问题中选择答案。
function getRandom(min, max) {
return Math.random() * (max - min) + min;
}
function test_2() {
var a = getRandom(0, 10) - 5;
while (a == 0)
a = getRandom(0, 10) - 5;
var b = getRandom(0, 10) - 5;
//create the div in which i add the radio buttons
var div = document.createElement('div');
div.setAttribute('class', 'parent');
div.setAttribute('id', '2');
document.body.appendChild(div);
//create the radio button and set its attributes
var radio1 = document.createElement('input');
var label1 = document.createElement('label');
label1.innerHTML = a * 4 + b;
label1.setAttribute('for', 'radio1');
radio1.setAttribute('type', 'radio');
radio1.setAttribute('value', a * 4 + b);
radio1.setAttribute('id', 'radio1');
radio1.setAttribute('name', 'answ');
radio1.innerHTML = a * 4 + b;
//add it to the div
div.appendChild(radio1);
div.appendChild(label1);
}
test_2();
【问题讨论】:
-
请简化代码示例,仅包含问题的相关部分。
-
所有
div和input[type=radio]元素都被赋予相同的id值。ids 在文档中必须是唯一的。 -
@YotamSalmon 代码不需要简化。这里没有什么过分的。相反,应该添加更多相关代码,以便我们可以重新创建场景。
-
没有足够的代码可以确定,但我怀疑问题在于
id属性在必须唯一时共享值。 -
是的,我认为 id 是问题。谢谢大家
标签: javascript html scope