jQuery:click function() ready 在 load 函数后不起作用



在jQuery 3.2.1中,如果我在加载函数之后构建复选框,那么当我单击复选框时,单击函数不起作用。

如果我在测试之前构建复选框,它会起作用!

如何对其进行编码,以便在加载函数中动态构建复选框后,单击函数能够工作?

<div id="idcheckbox">
</div>

$(window).on('load', function () {
$("#idcheckbox").append("<div class='custom-control custom-checkbox custom-control-inline'><input type='checkbox' class='custom-control-input' id=" + identifiant + " value=" + url + "><label class='custom-control-label' for=" + identifiant + ">" + url + "</label></div>");
});
$(document).ready(function () {
$("input[type='checkbox']").on('change', function () {
alert("0000");
});
$("input[type='checkbox']").on('click', function () {
alert("1111");
});
//solution 
$("#idcheckbox").on("click", "input[type='checkbox']", function () {
if ($("input[type='checkbox']").is(':checked')) {
alert("jQuery checked");
} else {
alert("jQuery no checked");
}
});

});

您正在document.ready上绑定事件,然后在window.load上构建控件,因此它将无法工作,因为事件已与现有控件绑定。如果您正在制作新控件,则需要在将控件添加到DOM之后再添加它。

var identifiant = "dynamic",
url = "www.google.com";
var counter = 1;
$(window).on('load', function() {
dynamicControl();
});
function dynamicControl() {
var id = identifiant + counter;
$("#idcheckbox").append("<div class='custom-control custom-checkbox custom-control-inline'><input type='checkbox' class='custom-control-input' id=" + id + " value=" + url + "><label class='custom-control-label' for=" + id + ">" + url + "</label></div>");
$("#" + id).on('change', function() {
alert('dynamic alert')
});
counter++;
}
$(document).ready(function() {
$("input[type='checkbox']").on('change', function() {
alert("0000");
});
$("input[type='checkbox']").on('click', function() {
alert("1111");
});
$("#Dynamic").on('click', dynamicControl);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="idcheckbox">
</div>
<input type='button' id='Dynamic' value='Add new checkbox'/>

最新更新