Javascript 在jquery中将li添加到ul时无法执行复选框事件

Javascript 在jquery中将li添加到ul时无法执行复选框事件,javascript,jquery,Javascript,Jquery,我试图实现checkbox checked事件,但似乎无法将其触发到添加到列表中的新元素。这是jquery代码 $("#button").click(function() { var toAdd = $("input[name=ListItem]").val(); $("ul").append( `<li class="" id=` + generateID() + `><input name="name" type

我试图实现checkbox checked事件,但似乎无法将其触发到添加到列表中的新元素。这是jquery代码

$("#button").click(function() {
    var toAdd = $("input[name=ListItem]").val();

    $("ul").append(
      `<li class="" id=` +
        generateID() +
        `><input name="name" type="checkbox" class="name" />` +
        listName +
        `</li>`
    );
  });

  $('input[type="checkbox"]').click(function() {
    if ($(this).prop("checked") == true) {
      alert("Checkbox is checked.");
    } else if ($(this).prop("checked") == false) {
      alert("Checkbox is unchecked.");
    }
  });

<ol>
<li id="1" class="">
<input name="name" type="checkbox" class="name"> List Name1 
</li>
</ol>

$(“#按钮”)。单击(函数(){
var toAdd=$(“输入[name=ListItem]”).val();
$(“ul”)。附加(
`
  • ` + 列表名+ `
  • ` ); }); $('input[type=“checkbox”]”)。单击(函数(){ if($(this).prop(“选中”)==true){ 警报(“复选框已选中”); }else if($(this).prop(“选中”)==false){ 警报(“复选框未选中”); } });
  • 名单名称1

  • 感谢您对现有和新元素的解决方案:

    $('body')。在('click','input[type=“checkbox”]”上,函数(){
    if($(this).prop(“选中”)==true){
    警报(“复选框已选中”);
    }else if($(this).prop(“选中”)==false){
    警报(“复选框未选中”);
    }
    
    });现有和新元素的解决方案:

    $('body')。在('click','input[type=“checkbox”]”上,函数(){
    if($(this).prop(“选中”)==true){
    警报(“复选框已选中”);
    }else if($(this).prop(“选中”)==false){
    警报(“复选框未选中”);
    }
    
    });
    可能需要委托事件监听器能否向我们展示html元素?我还有一个问题,如何在列表中检索id,因为这些id是随机数?可能需要委托事件监听器能否向我们展示html元素?我还有一个问题,由于这些id是随机数,如何在列表中检索id?仅代码的答案被视为劣质Hi@a.N.SINHA,谢谢。我还有一个问题,如何在列表中检索id,因为这些id是随机数?$('li').on('click',function(){alert($(this.prop('id'));});在获取测试变量$(“body”)时,我没有定义。在(“click”、“input[type=“checkbox”]”上,function(){if($(this).prop(“checked”)==true){let test;$(li”)。在(“click”上,function(){test=$(this.prop(“id”);});console.log(test);}否则如果($(this).prop(“checked”)==false){//alert(“复选框未选中。”);}仅代码的答案被视为劣质hi@A.N.SINHA,谢谢。我还有一个问题,如何在列表中检索id,因为这些id是随机数?$('li')。on('click',function(){alert($(this).prop('id');});我在获取测试变量$('body')时未定义。on('click',input[type=“Checkbox”],function(){if($(this).prop(“checked”)==true){let test;$($li”).on(“单击”,function(){test=$(this.prop(“id”);});console.log(test);}否则if($(this.prop(“checked”)==false){//警报(“复选框未选中”);}