繁体   English   中英

jQuery:click function() ready 加载后不起作用 function

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM