繁体   English   中英

如何为选中和未选中的复选框设置事件处理程序?

[英]How could I set up an event handler for my checkbox for checked and unchecked?

我正在使用 Bootstrap 5 和 jQuery 3.6.0,我一直在努力寻找解决方案,但我发现的一切都没有奏效,因为它已经过时了。

我基本上要做的就是为选中或未选中的复选框设置一个事件处理程序。 该复选框是 Bootstrap 开关样式的复选框。

我设法得到它,以便激活未检查部分的代码,但我认为它没有被正确激活。 但我无法得到它,以便事件在被检查时激活。

我的 HTML:

<div class="form-check form-switch" id="checkboxLondon">
              <input class="form-check-input" type="checkbox" id="flexSwitchCheckDefault">
              <label class="form-check-label" for="flexSwitchCheckDefault">London</label>
</div>

我的 jQuery/JS:

$('#checkboxLondon').click(function () {
    console.log("This works")
    if ($(this).is(":checked")){
      console.log("Checkbox is checked");
    } else if ($(this).is(":checked") == false) {    
      console.log("Checkbox is unchecked");
    }
});

使用.change()状态处理程序在你的复选框,不是在父DIV然后检查时复选框与检查.is()

 $('#flexSwitchCheckDefault').change(function(){ console.log($(this).is(':checked')) })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="form-check form-switch" id="checkboxLondon"> <input class="form-check-input" type="checkbox" id="flexSwitchCheckDefault"> <label class="form-check-label" for="flexSwitchCheckDefault">London</label> </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM