我认为说明 OP 与他所说的要求可能存在的问题已经足够重要了,所以我编写了这个 jsFiddle 来展示为每个单选按钮分配相同名称和将每个单选按钮的名称更改为不同之间的区别.
第一行中的单选按钮都可以选中...但是您将无法取消选中它们,因为它们没有任何东西可以关闭它们(没有其他同名的单选按钮可以关闭它们)。
第二行中的单选按钮将按照您期望单选按钮组的工作方式工作......一次只能检查一个单选按钮。
http://jsfiddle.net/2ENZP/1/
HTML:
<form name="quiz" method="post" action="evaluate.jsp">
<h3>Buttons with Differing Names</h3>
<fieldset id="buttonsDiffNames">
</fieldset>
<h3>Buttons with Same Names</h3>
<fieldset id="buttonsSameNames">
</fieldset>
<input type="submit">
</form>
Javascript:
var radioBtns = [
{id:0,name:"charles"},
{id:1,name:"diana"},
{id:2,name:"peter"},
{id:3,name:"sofia"},
{id:4,name:"reggie"},
{id:5,name:"jim"}
];
// set up templates for use by the examples, below.
var tmpl = '<input type="radio" name="{ID}" value="{ID}">{NAME}';
var tmpl2 = '<input type="radio" name="{ID}" value="{NAME}">{NAME}';
// This one will populate the first list, with buttons
// that all have different names
function populateWithDifferingNames(){
// get a ref to the fieldset we're going to add these to
var fieldSet = document.getElementById("buttonsDiffNames");
// create an array to act as a StringBuilder
var sb = [];
// loop through your dataset...
for(var i = 0; i < radioBtns.length; i++){
// add a string to the sb array, replacing the templated
// areas with the incremented radio button id and the name
// from the dataset
sb.push(tmpl.replace(/\{ID\}/gi,"q" + radioBtns[i].id).replace("{NAME}", radioBtns[i].name));
}
// set the fieldset's innerHTML to the joined string representation
// of the sb array
fieldSet.innerHTML = sb.join("\n");
}
// Same idea, but with matching names
function populateWithSameNames(){
var fieldSet = document.getElementById("buttonsSameNames");
var sb = [];
for(var i = 0; i < radioBtns.length; i++){
sb.push(tmpl2.replace(/\{ID\}/gi,"q").replace(/\{NAME\}/gi, radioBtns[i].name));
}
fieldSet.innerHTML = sb.join("\n");
}
window.onload = function() {
populateWithDifferingNames();
populateWithSameNames();
}();
</p>