动态复选框onchange不工作使用jquery

Dynamic checkbox onchange not working using jquery?

本文关键字:jquery 工作 复选框 onchange 动态      更新时间:2023-09-26

我使用jQuery创建了动态复选框,并在div中显示,我创建了复选框onchange函数。

静态复选框onchange函数工作,但当我生成动态复选框和相同的函数调用时,它不起作用

动态复选框代码:

$(document).on("click", "#item_modal", function() {
        $.ajax({
        url: '<?=base_url()?>extraItem',
        type: 'post',
        dataType: 'json',
        data: {itemId: id}
        })
        .done(function(data) {
             console.log(data);
            var extraItems = "";
            $.each(data, function(index, el) {
            extraItems+='<div class="col-md-4 col-lg-4"> <label style="width:100%"> <div class="col-md-6 col-lg-6 col-sm-6 col-xs-6"> <div style="font-size:14px;color:#fff;" class="checkbox"> <input name="product" value="'+el.amt+'" type="checkbox" id="p'+el.id+'"> <b>'+el.name+'</b> </div></div><div class="col-md-6 col-lg-6 col-sm-6 col-xs-6"> <p style="color:#fff;padding:10px;font-size:12px"> <span class="fa fa-rupee"></span> <b>'+el.amt+'</b> </p></div></label> </div>';
            });
            $('.extraItemList').append(extraItems);
            jQuery('#myModal .modal-content').html();
            $('#myModal').modal({
                "backdrop": "static"
            });
        });
    });

复选框Onchange功能:

$(document).ready(function() {
    $(":checkbox").on("change", function() {
        console.log("check");
    });    
});

Html Static复选框:It's working

<div class="col-md-12 col-lg-12" style="padding:0 34px;">
   <div class="col-md-4 col-lg-4">
      <label style="width:100%">
         <div class="col-md-6 col-lg-6 col-sm-6 col-xs-6">
            <div style="font-size:14px;color:#fff;" class="checkbox"> <input name="product" value="60.00" type="checkbox" id="p4" class="checkboxes"> <b>Extra Veg</b> </div>
         </div>
         <div class="col-md-6 col-lg-6 col-sm-6 col-xs-6">
            <p style="color:#fff;padding:10px;font-size:12px"> <span class="fa fa-rupee"></span> <b>60.00</b> </p>
         </div>
      </label>
   </div>
</div>
Html动态:
<div class="col-md-12 col-lg-12 extraItemList" style="padding:0 34px;">
</div>

我正在添加动态复选框。extraitemlist类

我花了很多时间来解决这个问题,但什么也没找到。

有解吗?因为这很奇怪

你可以这样绑定复选框:

$(document).ready(function() {
    $(".extraItemList").on("change", 'input[type="checkbox"]',  function() {
        console.log("check");
    });    
});

通过这样做,它将绑定到extraItemList类中的所有复选框类型的输入。

我希望这对你有帮助。

您应该像下面这样对动态元素使用事件委托。

$(".extraItemList").on("change", ":checkbox", function() {
    console.log("check");
});

变化

$(document).ready(function() {
    $(":checkbox").on("change", function() {
        console.log("check");
    });    
});

$(document).ready(function() {
    $(".extraItemList").on("change", ":checkbox",  function() {
        console.log("check");
    });    
});

如果你使用你的解决方案,jQuery会将事件绑定到当前可用的复选框,如果你使用我的解决方案,jQuery会将事件绑定到文档,并检查元素是否为复选框,然后触发事件。动态内容