使用jquery将选中的项目转移到列表的底部

Transfer a checked item to bottom of the list using jquery

本文关键字:转移 列表 底部 项目 使用 jquery      更新时间:2023-09-26

我想使用jquery(而不是angularjs)创建一个todo列表,将项目添加到列表中,如果选中了某个项目,则将该项目转移到列表的底部。使用jQuery我该如何做到这一点?

我很感激你的帮助。

我从以下代码开始:

HTML:

<html>
    <head>
        <title>My Page</title>
        <link rel="stylesheet" type="text/css" href="css/test02.css"/>
       <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script type="text/javascript" src="js/test02.js"></script>
    </head>
    <body>
        <div class="container" >
            <h1>Todos</h1>
            <input type="text"  id="new-text" placeholder="What do you need to do?">
            <input type="submit" id="add" value="Add">
            <ul id="todolist"></ul>

        </div>
    </body>
</html>

JS:

$(function() {
            $("#add").on('click', addListItem);
            $(document).on('click', '.done', finishItem);
        });
    function addListItem() {
        if($("#new-text").val() !== ''){
            var text = $("#new-text").val();
            $("#todolist").append('<li><input type="checkbox" id="mycheckbox" class="done"/>' + text + '</li>');
            $("#new-text").val('');
            }
        }                          
    }
    function finishItem() {
        if( $(this).parent().css('textDecoration') !== 'line-through' ){
            $(this).parent().css('textDecoration', 'line-through');       
        }else{
            $(this).parent().css('textDecoration', 'none');
        }
    }

首先,在"addLastItem"函数之后的JS代码中有一个多余的花括号。

我对你的代码有更多的建议:

  • 将所有jQuery元素保存在一个变量中以加快页面速度:
  • var$this=$(this),$parent=$this.parent()
  • 不是使用"text-decoration"属性来确定列表元素是否"完成"。。。
    if($(this).Pparent().css('textDecoration')!==='行通过'){…}
    …使用复选框的"checked"属性:
    if($this.is(':checked')){…}

为了将选中的项目移动到列表的底部,您可以使用jQuery的".append()"函数。

看看这把小提琴如果取消选中,我还使用了"prepend"函数将元素移动到列表的顶部。

function finishItem() {
    var $this = $(this),
        $parent = $this.parent();
    if ($this.is(':checked')) {
        $parent.css('textDecoration', 'line-through');
        $todolist.append($parent);
    } else {
        $parent.css('textDecoration', 'none');
        $todolist.prepend($parent);
    }
}

.appendTo("#todolist")将把当前元素移动到列表的末尾。

那么$(this).parent().css('textDecoration', 'line-through'); 在哪里

将其更改为$(this).parent().css('textDecoration', 'line-through').appendTo("#todolist");