gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:18:52 26 4
gpt4 key购买 nike

我想使用 jquery(不是 angularjs)创建一个待办事项列表,将项目添加到列表中,如果选中了一个项目,则将其转移到列表底部。我将如何使用 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(); 
  • Instead of using the "text-decoration" attribute to determine weather a list element is "done" ...
    if ($(this).parent().css('textDecoration') !== 'line-through' ) { ... }
    ... use the "checked" property of the checkbox:
    if ($this.is(':checked')) { ... } 

In order to move the checked item to the bottom of the list you can use jQuery's ".append()" function.

Check it out in this fiddle. I also used the "prepend" function to move the element to the top of the list if it gets unchecked.

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);
}
}

关于javascript - 使用 jquery 将选中的项目转移到列表底部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25557882/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com