选择带有 jQuery 标签的 "li" 项时遇到问题

Trouble selecting a "li" item with jQuery tag

我正在尝试创建一个简单的待办事项应用程序,它发布新项目并附加到 DOM 并在单击时删除该项目。我能够将待办事项附加到页面,但是当它们被点击时它们并没有被删除。我相信它与我的 onclick 事件处理程序有关,因为它没有正确选择 "li"。有什么想法吗?

代码如下:

<html>
<head>
    <script src='jquery-2.1.3.js'></script>
    <script src='handlebars-v2.0.0.js'></script>
</head>
<body>


        <!-- #TODO LIST
        Create textarea "todo item" and associated "submit button"
        When "submit button" is clicked
            take data entered into "todo item"
            append to empty div "todos" as Li item with id of the todo item
            Empty the "todo item"
        When a list item in "todos" is clicked delete item from "todos"
        -->


        <div>
            <textarea id = 'todoItem'></textarea>
            <button id = 'submitButton'>Post</button>
        </div>

        <div class = 'todos'>Items</div>

        <script>
            $("#submitButton").on("click", function(){
                var todo = $("#todoItem").val();
                $('<li>' + todo + '</li>').appendTo('.todos');
                $("#todoItem").val('');
            });
            $("li").on("click", function(){
                $('li').remove();
            });
        </script>
    </body>
    </html>

这里有几个问题:

  1. 您在 button 上没有点击事件来提交输入的文本
  2. $("li").on("click", function(){ 将不起作用,因为 li 是在 DOM 加载之后附加的,因此您需要在其他地方添加事件侦听器(例如 body ) 并将 li 添加为委托..ex: $("body").on("click", "li", function(){
  3. 你应该调用 $(this).remove(); 而不是 $("li").remove() 来删除实际点击的 li

FIDDLE

$("#submitButton").click(function(){
   var todo = $("#todoItem").val();
   $('<li>' + todo + '</li>').appendTo('.todos');
   $("#todoItem").val('');
});


$("body").on("click", "li", function(){
   $(this).remove();
});