method1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
label {
/* background-color: royalblue; */
width: 400px;
display: flex;
justify-content: space-evenly;
margin: auto;
}
.radioBox {
width: 60px;
border: 2px solid black;
border-radius: 10px;
}
.radioBoxColor {
background-color: rgb(23, 63, 63);
}
</style>
</head>
<body>
<label for="screenLink">
<div class="radioBox"><input type="radio" name="screenLink" value="linkHor" οnclick="getValue()">横屏</div>
<div class="radioBox"><input type="radio" name="screenLink" value="linkVer" οnclick="getValue()">竖屏</div>
</label>
</body>
</html>
<script>
var radio = document.getElementsByName("screenLink");
var radioBox=document.getElementsByClassName('radioBox')
function getValue() {
for (i = 0; i < radio.length; i++) {
radioBox[i].classList.remove('radioBoxColor')
if (radio[i].checked) {
radioBox[i].classList.add('radioBoxColor')
}
}
}
</script>
实现的思路是便利radio dom每次都检查他的checked属性 如果为true就是被选中的 将其值value返回出来拿到
method2
function getValue(obj) {
// method 2
var value = obj.value;
alert(value);
}
这个方法是onclick触发方法的时候传递一个参数this this代表的是当前对象 传到方法中直接打印他的value就可以了
method2
第三种方法则是在第二种的方法上更进一步 直接传递this.value 这样拿到的直接就是value值