如何將程式碼從 JavaScript 更改為 jQuery 來取消選中單選按鈕?


我們這裡有兩個單選按鈕,並且我們已經勾選了 −

<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 編輯器中選擇“使用 Live Server 開啟”。

輸出

輸出如下 −

更新時間: 03-Oct-2020

464 次瀏覽量

開始你的 職業生涯

透過完成課程獲得認證

開始使用
廣告
© . All rights reserved.