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

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.

主站蜘蛛池模板: 青河县| 西峡县| 南和县| 武冈市| 通化县| 黔东| 安顺市| 九江县| 时尚| 微山县| 汪清县| 彰化县| 柳林县| 类乌齐县| 通城县| 北安市| 翁源县| 大同县| 台山市| 德钦县| 阜阳市| 阿拉善左旗| 虞城县| 清涧县| 靖江市| 武城县| 广西| 兴文县| 扎囊县| 华安县| 玛沁县| 武强县| 辽源市| 绍兴市| 琼结县| 饶平县| 荥经县| 林周县| 乐业县| 洪洞县| 壶关县|