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

我试图实现复选框选中事件,但似乎无法将其触发到添加到列表中的新元素。这是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>


长风秋雁
浏览 217回答 1
1回答

慕桂英3389331

现有和新元素的解决方案:$('body').on('click', 'input[type="checkbox"]', function() {&nbsp; &nbsp; &nbsp; if ($(this).prop("checked") == true) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert("Checkbox is checked.");&nbsp; &nbsp; &nbsp; } else if ($(this).prop("checked") == false) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; alert("Checkbox is unchecked.");&nbsp; &nbsp; &nbsp; }});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript