如何将我的代码从 JavaScript 更改为 jQuery,以取消选中单选按钮?

jqueryweb developmentfront end technology更新于 2026/2/11 3:37:17

假设以下是我们的单选按钮,我们已将其设置为选中状态 −

<label>Gender</label>
<input type="radio" id="yourChoice" checked>Male
<input type="radio" id="yourChoice" checked> Female

要取消选中,请使用 jQuery 中的 prop() 将 checked 属性设置为 false −

$('input[id="yourChoice"]:checked').prop("checked", false);

示例

以下是代码 −

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
   <label>Gender</label>
   <input type="radio" id="yourChoice" checked>Male
   <input type="radio" id="yourChoice" checked> Female
</body>
<script>
   $('input[id="yourChoice"]:checked').prop("checked", false);
</script>
</html>

要运行上述程序,请将文件名保存为 anyName.html (index.html)。右键单击该文件,然后在 VS Code 编辑器中选择"使用实时服务器打开"选项。

输出

输出如下 −


相关文章