远程选中复选框时未检测到复选框更改
checkbox change not detected when checkbox is checked remotely
我有两个复选框。当检查第一个时,我也强制检查第二个。当第二个被选中时,我想切换一条消息。但是当检查第一个时,第二个没有检测到更改事件:
$(document).ready(function(){
$("#first").change(function(){
if ($(this).is(":checked")){
$("#second").prop('checked', true).attr("disabled","disabled");
} else {
$("#second").prop('checked', false).removeAttr("disabled");
}
});
$("#second").change(function(){
if ($(this).is(":checked")){
$("#alert").show();
} else {
$("#alert").hide();
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="first" type="checkbox">first
<input id="second" type="checkbox">second
<br><br>
<div id="alert" style="display:none">This is an alert</div>
对 dom 元素的逻辑更改不会生成事件。如果你想要一个事件运行 trigger('change')
就可以在事后生成一个事件。
您的方法没有按预期工作,因为当您动态设置某些内容时,它的事件不会像鼠标单击那样分派。
因此,您需要手动调度事件。
在jQuery中,可以使用.trigger()
。
$(document).ready(function(){
$("#first").change(function(){
if ($(this).is(":checked")){
$("#second").prop('checked', true).attr("disabled","disabled");
} else {
$("#second").prop('checked', false).removeAttr("disabled");
}
// ADDED THIS LINE
$('#second').trigger('change');
});
$("#second").change(function(){
if ($(this).is(":checked")){
$("#alert").show();
} else {
$("#alert").hide();
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="first" type="checkbox">first
<input id="second" type="checkbox">second
<br><br>
<div id="alert" style="display:none">This is an alert</div>
我有两个复选框。当检查第一个时,我也强制检查第二个。当第二个被选中时,我想切换一条消息。但是当检查第一个时,第二个没有检测到更改事件:
$(document).ready(function(){
$("#first").change(function(){
if ($(this).is(":checked")){
$("#second").prop('checked', true).attr("disabled","disabled");
} else {
$("#second").prop('checked', false).removeAttr("disabled");
}
});
$("#second").change(function(){
if ($(this).is(":checked")){
$("#alert").show();
} else {
$("#alert").hide();
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="first" type="checkbox">first
<input id="second" type="checkbox">second
<br><br>
<div id="alert" style="display:none">This is an alert</div>
对 dom 元素的逻辑更改不会生成事件。如果你想要一个事件运行 trigger('change')
就可以在事后生成一个事件。
您的方法没有按预期工作,因为当您动态设置某些内容时,它的事件不会像鼠标单击那样分派。
因此,您需要手动调度事件。
在jQuery中,可以使用.trigger()
。
$(document).ready(function(){
$("#first").change(function(){
if ($(this).is(":checked")){
$("#second").prop('checked', true).attr("disabled","disabled");
} else {
$("#second").prop('checked', false).removeAttr("disabled");
}
// ADDED THIS LINE
$('#second').trigger('change');
});
$("#second").change(function(){
if ($(this).is(":checked")){
$("#alert").show();
} else {
$("#alert").hide();
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="first" type="checkbox">first
<input id="second" type="checkbox">second
<br><br>
<div id="alert" style="display:none">This is an alert</div>