[英]jQuery:click function() ready doesn't work after the load function
在 jQuery 3.2.1 中,如果我在加載 function 后構建復選框,單擊 function 時單擊復選框不起作用。
如果我在測試之前構建了復選框,它就可以工作!
如何對其進行編碼,以便在加載 function 中動態構建復選框后單擊 function 起作用?
<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'/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.