通过 jQuery,您所要求的绝对是可能的。这是确切的解决方案:
$('#div1 form input:radio').change(function() {
// Grabs all other radio buttons in the form, and
// deselects all but the one which was clicked on.
$('#div1 form input:radio').not(this).prop('checked', false);
});
此外,任何 HTML 元素之间的 ID 必须 100% 唯一。虽然这不会阻止上述代码工作,但如果您尝试根据其 ID 选择一个项目,例如$('#r1')
只会返回其中一个元素,而不是所有元素。
对于完整的实施:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.2.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
$('#div1 form input:radio').change(function() {
// Grabs all other radio buttons in the form, and
// deselects all but the one which was clicked on.
$('#div1 form input:radio').not(this).prop('checked', false);
});
});
</script>
<div id="div1">
<form>
<input type="radio" name="r1" id="r1" value="r1 value 1" />
<input type="radio" name="r1" id="r1" value="r1 value 2" />
<input type="radio" name="r1" id="r1" value="r1 value 3" />
<input type="radio" name="r2" id="r2" value="r2 value 1" />
<input type="radio" name="r2" id="r2" value="r2 value 2" />
<input type="radio" name="r2" id="r2" value="r2 value 3" />
<input type="radio" name="r3" id="r3" value="r3 value 1" />
<input type="radio" name="r3" id="r3" value="r3 value 2" />
<input type="radio" name="r3" id="r3" value="r3 value 3" />
</form>
</div>
</body>
</html>
对于 IE 6、7 和 8 兼容性:
Replace:
<script type="text/javascript" src="http://code.jquery.com/jquery-2.0.2.min.js"></script>
With:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>