不经常使用就会忘记,此处做一个笔记,方便以后使用
第一种,也是最简单的一种方式实现,
<%--
Created by IntelliJ IDEA.
Date: 2019/7/15
Time: 9:46
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>测试JSP页面中的radio选项</title>
</head>
<%--<script type="text/javascript" src="js/jquery/jquery-1.11.1.min.js"></script>--%>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<body>
<form action="" method="get">
<div class="">
<strong>生活组成:</strong>
<label><input type="radio" name="lifeType" value="1" checked="checked"/>休息</label>
<label><input type="radio" name="lifeType" value="2" />工作</label>
<label><input type="radio" name="lifeType" value="3" />学习</label>
</div>
获取选择的值: <label id="value" name="value"/>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("input:radio[name='lifeType']").click(function(){
var lifeType = $('input[name="lifeType"]:checked').val();
if (lifeType == '1' || lifeType == '' || lifeType == null) {
lifeType = "值为1";
document.getElementById("value").innerHTML = lifeType;
} else if (lifeType == '2') {
lifeType = "值为2";
document.getElementById("value").innerHTML = lifeType;
} else if (lifeType == '3') {
lifeType = "值为3";
document.getElementById("value").innerHTML = lifeType;
}
});
});
</script>
</body>
</html>
直接运行上面的程序,即可实现单选按钮的点击功能,运行截图如下所示
以上是最简单的一种方式,还有其他的实现方式,
第二种,以其他方式标签,实例如下所示:
<%--
Created by IntelliJ IDEA.
Date: 2019/7/15
Time: 9:46
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>测试JSP页面中的radio选项</title>
</head>
<%--<script type="text/javascript" src="js/jquery/jquery-1.11.1.min.js"></script>--%>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<body>
<form action="" method="get">
<div class="" id="test">
<strong>生活组成-test:</strong>
<label><input type="radio" name="lifeType" value="1" checked="checked"/>休息</label>
<label><input type="radio" name="lifeType" value="2" />工作</label>
<label><input type="radio" name="lifeType" value="3" />学习</label>
</div>
获取选择的值: <label id="value" name="value"/>
</form>
<script type="text/javascript">
// $(document).ready(function () {
// $("input:radio[name='lifeType']").click(function(){
// show();
// });
// });
$(document).on("click", "#test input", function (event) {
show();
});
function show() {
var lifeType = $('input[name="lifeType"]:checked').val();
if (lifeType == '1' || lifeType == '' || lifeType == null) {
lifeType = "值为1--";
document.getElementById("value").innerHTML = lifeType;
} else if (lifeType == '2') {
lifeType = "值为2--";
document.getElementById("value").innerHTML = lifeType;
} else if (lifeType == '3') {
lifeType = "值为3--";
document.getElementById("value").innerHTML = lifeType;
}
}
</script>
</body>
</html>
运行结果如下所示:
以上是2中实现单选按钮事件的方式,可以根据组件的不同,修改第2中方式中的
$(document).on("click", "#test input", function (event) 中的"#test input"这部分内容即可