我使用多个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>我已经尝试了多个JS代码,但似乎都不起作用。示例
$('.custom-control').on('change', function (e) {
let value = this.value;
let test = $(e).target.checked;
});我还尝试使用input标记的class。
发布于 2020-09-20 02:59:04
checkbox具有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">
发布于 2020-09-20 03:13:12
尝试使用jQuery,如下所示
$(document).on('change', '.custom-control', function (e) {
let test = $(this).is(':checked');
console.log(test);
});https://stackoverflow.com/questions/63972287
复制相似问题