HTML
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
<title>单选/复选/开关的选中和取消 - 光年(Light Year Admin)后台管理系统模板</title>
<link rel="icon" href="favicon.ico" type="image/ico">
<meta name="keywords" content="LightYear,光年,后台模板,后台管理系统,光年HTML模板">
<meta name="description" content="LightYear是一个基于Bootstrap v3.3.7的后台管理系统的HTML模板。">
<meta name="author" content="yinqi">
<link href="http://lyear.itshubao.com/iframe/css/bootstrap.min.css" rel="stylesheet">
<link href="http://example.itshubao.com/demo/css/materialdesignicons.min.css" rel="stylesheet">
<link href="http://lyear.itshubao.com/iframe/css/style.min.css" rel="stylesheet">
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header"><h4>单选/复选/开关的绑定点击事件</h4></div>
<div class="card-body">
<p>实际应用中,有很多小伙伴会再上面绑定click事件,从而发现这个click会执行两次,这是因为label上执行之后,会冒泡到input上再执行一次。</p>
<div class="form-group">
<label class="lyear-radio radio-inline radio-primary test-radio-1">
<input type="radio" name="a1" value="羽毛球"><span>执行两次</span>
</label>
</div>
<div class="form-group">
<label class="lyear-radio radio-inline radio-primary test-radio-2">
<input type="radio" name="a2" value="羽毛球"><span>执行一次</span>
</label>
</div>
<div class="form-group">
<label class="lyear-checkbox checkbox-inline checkbox-primary test-checkbox-1">
<input type="checkbox" name="b[]" value="篮球"><span>篮球</span>
</label>
</div>
<div class="form-group">
<label class="lyear-checkbox checkbox-inline checkbox-primary test-checkbox-2">
<input type="checkbox" name="b[]" value="篮球"><span>篮球</span>
</label>
</div>
<div class="form-group">
<label class="lyear-switch switch-primary test-switch-1">
<input type="checkbox" name="c1" value="on">
<span></span>
</label>
</div>
<div class="form-group">
<label class="lyear-switch switch-primary test-switch-2">
<input type="checkbox" name="c2" value="on">
<span></span>
</label>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="http://lyear.itshubao.com/iframe/js/jquery.min.js"></script>
<script type="text/javascript" src="http://lyear.itshubao.com/iframe/js/bootstrap.min.js"></script>
</body>
</html>
JavaScript
$(document).ready(function() {
$('.test-radio-1').on('click', function(e) {
alert('直接绑定到单选框的label,会执行两次');
});
$('.test-radio-2 input').on('click', function(e) {
alert('直接绑定到input上');
});
$('.test-checkbox-1').on('click', function(e) {
alert('直接绑定到复选框的label,会执行两次');
});
$('.test-checkbox-2 input').on('click', function(e) {
alert('直接绑定到input上');
});
$('.test-switch-1').on('click', function(e) {
alert('直接绑定到开关的label,会执行两次');
})
// 另一种的解决方案,先阻止事件的动作,由自己来操作input的选中与否
$('.test-switch-2').on('click', function(e) {
e.preventDefault();
var inputObj = $(this).find('input');
var s = inputObj.prop('checked');
inputObj.prop('checked', !s);
})
});