[分享] 利用偽類, 找出 checked 的方法

Lastor
Code 隨筆放置場
2 min readAug 14, 2019

本章節利用 Array.prototype.forEach() 迭代 + if 的方式,
來找出屬性checked 為 true 者↓

AlphaPos.prototype.getCheckedValue = function (inputName) {
let selectedOption = ''
// 用迭代去逐個比對, 找出屬性checked為true者
document.querySelectorAll(`[name=${inputName}]`).forEach(item => {
if (item.checked) {
selectedOption = item.value
}
})
return selectedOption
}

這邊提供另一個方法, 是利用CSS的偽類。
當 input 被checked時, 會激活該 input 的偽類 「:checked」。

因為 radio 必定只存在一個 checked,
所以可以使用 querySelector 單選, 配合CSS Selector, 直接指到被checked的元素。

AlphaPos.prototype.getCheckedValue = function (inputName) {
// 太長了, 用變數裝一下
const input = document
.querySelector('input[name="${inputName}"]:checked')

return input.value
}

如果使用 jQuery 來選取, code還可以寫更短

AlphaPos.prototype.getCheckedValue = function (inputName) {
return $(`input[name="${inputName}"]:checked`).val()
}

--

--

Lastor
Code 隨筆放置場

Web Frontend / 3D Modeling / Game and Animation. 設計本科生,前遊戲業 3D Artist,專擅日本動畫與遊戲相關領域。現在轉職為前端工程師,以專業遊戲美術的角度涉足 Web 前端開發。