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

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!

主站蜘蛛池模板: 长白| 鹰潭市| 宣城市| 长武县| 仁寿县| 京山县| 巨野县| 江源县| 麦盖提县| 安陆市| 故城县| 安陆市| 淳化县| 成安县| 平乐县| 合水县| 海兴县| 江西省| 平安县| 南昌市| 宜阳县| 昌宁县| 宁夏| 南江县| 屏东市| 阜平县| 信丰县| 杨浦区| 浮山县| 志丹县| 万源市| 大冶市| 资兴市| 霍林郭勒市| 许昌县| 新野县| 资中县| 曲麻莱县| 万山特区| 福安市| 莱芜市|