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

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!

主站蜘蛛池模板: 金昌市| 济阳县| 南城县| 濉溪县| 遂宁市| 巨鹿县| 鄄城县| 台州市| 南充市| 临澧县| 开远市| 务川| 寿阳县| 平遥县| 梨树县| 博爱县| 威远县| 张掖市| 巴彦淖尔市| 开远市| 达拉特旗| 广德县| 齐齐哈尔市| 伊川县| 原阳县| 龙泉市| 绥德县| 读书| 宕昌县| 大邑县| 冷水江市| 忻城县| 尚志市| 呼玛县| 韶山市| 绥阳县| 凤台县| 江达县| 南乐县| 广平县| 佳木斯市|