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

Time for action – removing a task from the list

Now that we can add tasks to the list, let's add the ability to remove tasks. To do this we'll need a delete button for each task in the list. We'll add the code to create the button in the addTaskElement() method. You can find the code for this section in Chapter 1/example1.2.

function addTaskElement(taskName)
{
    var $task = $("<li></li>");
    var $delete = $("<button class='delete'>X</button>");
    $task.append($delete)
         .append("<span class='task-name'>" + taskName +
                 "</span>"); 
    $delete.click(function() { $task.remove(); });
}

The first thing this method does is create a new <button> element with a class of delete. Then it creates the list item element as we did before, except that first it appends the delete button and then appends the task name. Note that we are now wrapping the task name in a <span class='task-name'> element to help us keep track of it. Last we add a click event handler to the delete button. To delete the task from the list element we simply call the remove() method to remove it from the DOM. Voila, it's gone!

主站蜘蛛池模板: 大宁县| 河间市| 崇左市| 香格里拉县| 堆龙德庆县| 赫章县| 邛崃市| 宿迁市| 清新县| 滕州市| 青海省| 长垣县| 大安市| 集贤县| 双鸭山市| 西丰县| 宁陵县| 乌苏市| 外汇| 永善县| 通河县| 枞阳县| 县级市| 嘉定区| 高安市| 宿迁市| 汾阳市| 图木舒克市| 区。| 西充县| 栖霞市| 务川| 公安县| 玉田县| 三穗县| 罗源县| 同仁县| 临泉县| 枝江市| 博湖县| 和林格尔县|