Bootstrap 4 开关更改事件将不起作用

Sug*_*ree 3 javascript jquery bootstrap-4

我正在使用Bootstrap 4 switches通过追加方式加载到页面上的多个内容JS,并且需要在切换更改时调用函数。当我在 中添加开关时,以下示例有效HTML,但是当我在JS页面加载后动态加载它们时,它将不起作用。我不想为此使用任何其他外部库!

<div class="custom-control custom-switch">
  <input type="checkbox" class="custom-control-input" id="customSwitch1">
  <label class="custom-control-label" for="customSwitch1">Toggle this switch element</label>
</div>
Run Code Online (Sandbox Code Playgroud)

我尝试了多个JS代码,但似乎都不起作用。例子

$('.custom-control').on('change', function (e) {
  let value = this.value;
  let test = $(e).target.checked;
});
Run Code Online (Sandbox Code Playgroud)

还尝试使用class标签input

gae*_*noM 7

复选框具有选中属性

因此使用:

let test = e.target.checked;
Run Code Online (Sandbox Code Playgroud)

因为您动态添加开关,所以您需要委托更改事件:

$(document).on('change', '.custom-control', function (e) {
Run Code Online (Sandbox Code Playgroud)

片段:

let test = e.target.checked;
Run Code Online (Sandbox Code Playgroud)
$(document).on('change', '.custom-control', function (e) {
Run Code Online (Sandbox Code Playgroud)