简体   繁体   English

使用JQuery一次删除一个项目

[英]Remove items one at a time using JQuery

I am trying to create a to-do list using HTML/CSS, Javascript and JQuery. 我正在尝试使用HTML / CSS,Javascript和JQuery创建待办事项列表。 The problem I have occurs when I try to delete an item off the list. 当我尝试删除列表中的项目时,出现了我遇到的问题。 Here is the Javascript. 这是Javascript。

$(document).ready(function(){
        $('#add').click(function(){
            if($('#input').val() != '')
                $('.container').append('<p class="todo">'+$('#input').val()+'</p><span class="del">&times</span><br/>');
        });

      $(document).on('click','.del',function(){
        $(this).click(function(){
            $('.todo').hide(); 
        });
      });
    });

The HTML HTML

<body>
    <h1 class="header">To-Do List</h1>
    <hr/>
    <br/>
    <input type="text" id="input"/>
    <button id="add">Add</button>
    <br/>
    <br/>
    <div class="container">
    </div>
</body>

What the above does is it removes all of the dynamically generated todo [paragraph] elements when a single del element [an x] is clicked. 上面的操作是,当单击单个del元素[x]时,它将删除所有动态生成的todo [paragraph]元素。 I am asking how to change the code so clicking the del element removes the todo element that it was generated with. 我在问如何更改代码,因此单击del元素会删除生成它的todo元素。 I understand I can use ids but I feel that is too cumbersome. 我知道我可以使用ID,但是我觉得这太麻烦了。 Thanks for the help. 谢谢您的帮助。

You can use .prev() to hide only the immediate previous sibling .todo paragraph of clicked .del : 您可以使用.prev()仅隐藏单击的.del前一个同级.todo段落:

$('.container').on('click','.del',function(){
    $(this).prev().hide(); 
});

Also take note that you don't need to use .click() event for .del any more since you've already using event delegation to attach the click event to them as well as using closest static parent for delegated event instead of $(document) . 另请注意,您不再需要将.del .click()事件用于.del因为您已经在使用事件委托将click事件附加到事件上,并且对委托事件使用了最接近的静态父对象而不是$(document)

Try this jQuery , this also hides the 'x': 试试这个jQuery ,这也会隐藏'x':

          $(document).on('click','.del',function(){
                $(this).hide(); 
                $(this).prev().hide();
          });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM