範圍當我改變的第一個複選框,我想改變VAR theSame
,但似乎並不在if(theSame == 1);
改變,但它在alert("b"+theSame)
變化。如何處理這個?關於在JavaScript
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var theSame = 1;
$("input[name='thesame']").change(function(){
theSame = $(this).is(":checked") ? 1 : 0;
alert("a"+theSame);
});
if(theSame == 1){
$(".check_list input").change(function(){
alert("b"+theSame);
});
}
});
</script>
</head>
<body>
<input type="checkbox" name="thesame">same
<br>
<div class="check_list">
<input type="checkbox" name="son">ppp
<input type="checkbox" name="son">ppp
<input type="checkbox" name="son">ppp
</div>
</body>
</html>
謝謝你,這是我想要實現:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input[name='thesame']").change(function(){
var theSame = this.checked ? 1 : 0;
show(theSame)
});
function show(i){
if(i == 1){
$(".check_list input").change(function(){
var inputName = $(this).attr("name");
$("input[name=" + inputName + "]").attr("checked",this.checked)
});
}else{
$(".check_list input").unbind("change")
}
}
});
</script>
</head>
<body>
<input type="checkbox" name="thesame" class="check-all">same
<br>
<div class="check_list">
<input type="checkbox" name="son">ppp
<input type="checkbox" name="sister">ppp
<input type="checkbox" name="dog">ppp
</div>
<hr>
<div class="check_list">
<input type="checkbox" name="son">ppp
<input type="checkbox" name="sister">ppp
<input type="checkbox" name="dog">ppp
</div>
<hr>
<div class="check_list">
<input type="checkbox" name="son">ppp
<input type="checkbox" name="sister">ppp
<input type="checkbox" name="dog">ppp
</div>
</body>
</html>
附註 - 不要使用'$(this).is(「:checked」)'。你可以使用'this.checked',它* *更快*表示*和*更易於閱讀。 [一個很酷的技巧,你可以使用](http://stackoverflow.com/questions/61088/hidden-features-of-javascript/2243631#2243631)這裏是'+ this.checked'而不是'this.checked? 1:0'。 –
你期待什麼發生? 'if(theSame == 1){'將始終運行,因爲您剛剛將'theSame'設置爲1。 –