Bootstrap 4开关(change)事件无法正常工作

3

我正在使用多个由 JS 添加到页面上的 Bootstrap 4 开关,并且需要在开关更改时调用函数。以下示例在我将开关添加到 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>

我尝试了多个JS代码,但似乎都没有起作用。例如:

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

我也尝试使用 input 标签的 class.

2个回答

7

复选框具有checked属性。

因此使用:

let test = e.target.checked;

因为你动态添加了开关,所以需要委托change事件:
$(document).on('change', '.custom-control', function (e) {

代码片段:

$(document).on('change', '.custom-control', function (e) {
    let test = e.target.checked;
    console.log(test);
});

$('body').append('<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>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">


刚刚编辑了我的问题。问题在于开关是通过JS动态加载的。 - Sugafree
运行得非常完美。谢谢。现在还不能接受它作为答案,但两分钟后会接受。 - Sugafree

0

尝试使用jQuery作为替代方案

$(document).on('change', '.custom-control', function (e) {
    let test = $(this).is(':checked');
    console.log(test);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接