【问题标题】:checkbox change not detected when checkbox is checked remotely远程检查复选框时未检测到复选框更改
【发布时间】: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 &nbsp;&nbsp;&nbsp;
<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

标签: jquery checkbox onchange


【解决方案1】:

对 dom 元素的逻辑更改不会产生事件。如果您希望事件发生后在其上运行trigger('change') 以生成事件。

【讨论】:

    【解决方案2】:

    您的方法没有按预期工作,因为当您动态设置某些内容时,它的事件不会像鼠标点击那样被调度。

    因此,您需要手动调度事件。

    在 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 &nbsp;&nbsp;&nbsp;
    <input id="second" type="checkbox">second
    <br><br>
    <div id="alert" style="display:none">This is an alert</div>

    【讨论】:

      猜你喜欢
      • 2016-01-19
      • 1970-01-01
      • 1970-01-01
      • 2011-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多