在JavaScript中,要设置一个radio
(单选按钮)为选中状态并且使其不可更改,可以通过以下步骤实现:
checked
属性。disabled
属性。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Radio Button Example</title>
</head>
<body>
<form>
<input type="radio" id="option1" name="options" value="Option 1">
<label for="option1">Option 1</label><br>
<input type="radio" id="option2" name="options" value="Option 2" checked disabled>
<label for="option2">Option 2 (Selected and Disabled)</label><br>
<input type="radio" id="option3" name="options" value="Option 3">
<label for="option3">Option 3</label>
</form>
<script>
// 通过JavaScript设置第二个单选按钮为选中且不可更改
document.addEventListener("DOMContentLoaded", function() {
var option2 = document.getElementById("option2");
option2.checked = true;
option2.disabled = true;
});
</script>
</body>
</html>
id
和for
属性用于关联标签和单选按钮,提高可访问性。option2
)初始状态为选中且禁用。DOMContentLoaded
事件确保DOM完全加载后再执行脚本。checked
属性为true
,disabled
属性为true
。通过上述方法,可以有效地设置单选按钮为选中且不可更改的状态,满足特定需求。
领取专属 10元无门槛券
手把手带您无忧上云