첫 번째 확인란을 변경하면 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'를 사용할 수 있습니다. * this * check *는 * 많이 * 더 빨리 수행하고 * 읽기 쉽습니다. [사용할 수있는 멋진 트릭] (http://stackoverflow.com/questions/61088/hidden-features-of-javascript/2243631#2243631) 여기에'this.checked? '대신'+ this.checked'가 있습니다. 1 : 0'이다. –
당신은 무엇을 기대하고 있습니까? 'theSame'을 1로 설정하면'if (theSame == 1) {'내부의 코드는 항상 실행됩니다. –