追加jQuery工作,但onclick不工作


Append jQuery working but onclick is not working

我有过滤器的产品类型,这是通过ajax创建的每个条目在数据库:

HTML部分:

<ul id="foodtype"></ul>
显示过滤器的Ajax代码:
    function showtypes(){
        $.ajax({
          type: "POST",
          url: "ajax/incl/showtype",
          data:'',
          dataType : 'json',
          cache: false,
          success: function(records1){
                $('#foodtype').html(makefoodType(records1));
          }
        });
       }
       function makefoodType(data1){
          var tbl_body = "";
            $.each(data1, function() {
              var tbl_row = "",
                  currRecord = this;
              $.each(this, function(k1 , v1) {
            tbl_row += "<li><input type=checkbox id="+v1+" name="+v1+" /> 
                        <span style=font-size:14px>"+v1+"</span></li>";
              })
              tbl_body += tbl_row;
            })
        return tbl_body;
      } 

类别得到正确显示,但当我选择复选框然后下面的代码需要执行

 function getFilterOptions(){
   var opts = [d,de];
   $checkboxes.each(function(){
     if(this.checked){
       opts.push(this.id);
   }
  return opts;
  }
  var $checkboxes = $("input:checkbox");
  $checkboxes.on("change", function(){
    var opts = getFilterOptions();
    updateProducts(opts);
  });

我想要复选框的ID被推到页面有php代码。但是在勾选复选框时什么也没有发生。注意:当我查看源代码,然后<ul id="foodtype"></ul>代码保持不变。没有显示<li>元素:

您需要使用事件委托。监听复选框所在的容器上的单击事件。因此,在动态添加它们之后,click事件将冒泡到容器中。

这是因为var $checkboxes = $("input:checkbox");在ajax完成之前被执行,因此没有元素。

改变

$(document).on("change", "input:checkbox", function() {
    var opts = getFilterOptions();
    updateProducts(opts);
});