javascript - 为什么这里的alert会执行2次?
本文介绍了javascript - 为什么这里的alert会执行2次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
这是一个把radio修饰后的按钮组,实现按下一个按钮,颜色变深,再按另一个按钮,之前变深的按钮恢复,此刻被按的按钮变深色。
绑定事件中的alert(value);会提示2次?请问是怎么回事?
CSS部分可忽略,直接看最后jquery。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>toggle radio</title>
<script src="http://cdn.bootcss.com/jquery/2.1.4/jquery.min.js"></script>
<style>
body {
font-family:sans-serif;
}
.toggle {
margin:4px;
background-color:#EFEFEF;
border-radius:4px;
border:1px solid #D0D0D0;
overflow:auto;
float:left;
}
.toggle label {
/*float:left;*/
width:4.0em;
}
.toggle label span {
text-align:center;
padding:3px;
display:block;
cursor: pointer;
}
.toggle label input {
position:absolute;
top:-20px;
}
.toggle .input-checked /*, .bounds input:checked + span works for firefox and ie9 but breaks js for ie8(ONLY) */ {
background-color:#404040;
color:#F7F7F7;
}
.toggle input:checked + span {
background-color:#404040;
color:#F7F7F7;
}
</style>
</head>
<body>
<div class="toggle">
<label><input type="radio" name="toggle" value="s01e01"><span>s01e01</span></label>
</div>
<div class="toggle">
<label><input type="radio" name="toggle" value="s01e02"><span>s01e02</span></label>
</div>
<div class="toggle">
<label><input type="radio" name="toggle" value="s01e03"><span>s01e03</span></label>
</div>
</body>
</html>
<script>
$('label').click(function(){
$(this).children('span').addClass('input-checked');
var value = $(this).children('input').val();
$(this).parent('.toggle').siblings('.toggle').children('label').children('span').removeClass('input-checked');
alert(value);
});
</script>
解决方案
这个原因很有意思,我开始以为是事件冒泡。但是想想不对。然后代码改为:
$('label').click(function(event){
console.log(event.target.type);
$(this).children('span').addClass('input-checked');
var value = $(this).children('input').val();
$(this).parent('.toggle').siblings('.toggle').children('label').children('span').removeClass('input-checked');
console.log(value);
});
event.target.type
主要是这个会触发两个一个是undefined
一个是radio
。因为label关联的radio也被有一个关联操作。当label被点击时,默认radio也被点击了一次。
解决方法你可以
<div class="label">
<input type="radio" name="toggle" value="s01e03">
<span>s01e03</span>
</div>
$('.label').click(function(){});
其实也可以这样写,因为你本身就是要控制span
,所以直接绑定到span
上。
$('span').click(function () {
var i = $('span').index($(this));
$(this).addClass('input-checked');
var value = $('input').eq(i).val();
$('span').not($(this)).removeClass('input-checked');
console.log(value);
})
然后DOM结构不需要改。
这篇关于javascript - 为什么这里的alert会执行2次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文