JavaScript 获取网页加载时选中的 Radio 按钮值
<!DOCTYPE html>
<html>
<head>
<title>Get Selected Radio Value</title>
</head>
<body>
<label><input type="radio" name="gender" value="male"> Male</label>
<label><input type="radio" name="gender" value="female"> Female</label>
<label><input type="radio" name="gender" value="other"> Other</label>
<script>
window.addEventListener('DOMContentLoaded', function() {
// 获取所有的radio元素
var radios = document.querySelectorAll('input[type="radio"]');
// 给每个radio添加点击事件监听器
radios.forEach(function(radio) {
radio.addEventListener('click', function() {
// 获取选中的radio的值
var selectedValue = document.querySelector('input[name="gender"]:checked').value;
console.log(selectedValue);
});
});
// 触发第一个radio的点击事件,即选中第一个radio
radios[0].click();
});
</script>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/pWxK 著作权归作者所有。请勿转载和采集!