【发布时间】:2017-11-06 15:28:57
【问题描述】:
我有两个复选框。检查第一个时,我也强制检查第二个。当第二个被选中时,我想切换一条消息。但是在检查第一个时,第二个没有检测到更改事件:
$(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>
【问题讨论】:
-
旁注,不要做
$(this).is(":checked"),只做this.checked。您已经拥有该元素,并且选中它是一个随时可用的属性。没有理由创建 jQuery 对象并使用方法来获取您已经可用的属性。 -
所以你想在一个禁用的元素上添加一个事件?
-
触发器适用于已接受答案中的禁用元素。 @MasterYoda