当我更改第一个复选框时,我想更改var theSame
,但在if(theSame == 1);
中似乎没有更改
但它在alert("b"+theSame)
中更改。如何处理呢?
<!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>
最佳答案
这实际上不是范围的问题,而是更多的异步性。让我们逐步执行代码:
$(document).ready(function(){
// Define function-scope variable `theSame`, assign it a value of `1`
var theSame = 1;
// Bind a `change` event handler to an element, this function will run later!
$("input[name='thesame']").change(function(){
theSame = +this.checked;
alert("a"+theSame);
});
// At this point, `theSame` has not changed from its original value!
if(theSame == 1){
$(".check_list input").change(function(){
// Here, however, `theSame` may have had its value changed
alert("b"+theSame);
});
}
});
因此,正如您所看到的,当
if
语句运行时,它将始终具有1
的值,因为直到执行此代码之后,该值才被更改。如果将
if
语句移到事件处理程序内部,则会看到不同的结果:$(".check_list input").change(function(){
if(theSame){
alert("b"+theSame);
}
});
在这里,只有
theSame
为1
时,您才会看到警报。关于javascript - 关于JavaScript中的范围,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8151122/