官术网_书友最值得收藏!

Time for action – moving tasks within the list

While we're at it, let's add buttons to move tasks up and down in the list. For this we'll add some more code to the addTaskElement() method. First we need to create move-up and move-down buttons, and then add them to the list element along with the delete button.

function addTaskElement(taskName)
{
    var $task = $("<li></li>");
    var $delete = $("<button class='delete'>X</button>");
    var $moveUp = $("<button class='move-up'>^</button>");
    var $moveDown = $("<button class='move-up'>v</button>");
    $task.append($delete)
        .append($moveUp)
        .append($moveDown)
        .append("<span class='task-name'>" + taskName +
                "</span>");
    $("#task-list").append($task);
    
    $delete.click(function() { $task.remove(); });
    $moveUp.click(function() {
        $task.insertBefore($task.prev());
    });
    $moveDown.click(function() {
        $task.insertAfter($task.next());
    });
}

When the move up or move down button is clicked, it finds the previous or next task element using the prev() and next() methods. Then it uses the jQuery insertBefore() and insertAfter() methods to move the task element up or down in the tasklist.

What just happened?

We added buttons to each task element so that we can delete them or move them up and down in the order of the list. We learned how to use the jQuery remove(), insertBefore(), and insertAfter() methods to modify the DOM.

主站蜘蛛池模板: 石门县| 望都县| 石家庄市| 江源县| 绥阳县| 双牌县| 徐水县| 武定县| 绥芬河市| 仲巴县| 孙吴县| 淳安县| 新巴尔虎右旗| 东山县| 乌拉特前旗| 台东县| 沙河市| 南和县| 宾川县| 八宿县| 石首市| 进贤县| 株洲县| 永顺县| 盐城市| 鹤山市| 慈利县| 宜丰县| 哈密市| 泗水县| 黄大仙区| 辽宁省| 舒兰市| 黑水县| 德兴市| 西乡县| 黎平县| 南岸区| 闸北区| 广灵县| 灵寿县|