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

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!

主站蜘蛛池模板: 鲜城| 博乐市| 平定县| 壶关县| 弋阳县| 晋州市| 西充县| 宝坻区| 象州县| 平阳县| 武功县| 射阳县| 岳阳县| 克拉玛依市| 彭山县| 喀喇沁旗| 兴业县| 浦北县| 西宁市| 仙桃市| 上杭县| 勐海县| 民乐县| 镇雄县| 西华县| 宜城市| 婺源县| 丰镇市| 松阳县| 巴林右旗| 扎赉特旗| 南投县| 凯里市| 南昌县| 霞浦县| 泰顺县| 北辰区| 阳西县| 阿拉善左旗| 遂溪县| 卓资县|