2015-12-14 37 views
-3

在我的jQuery中,我添加了一系列li元素,並且每個li元素都有一個是子元素的按鈕。我想要做的是做一個點擊事件處理程序來附加到按鈕,這將刪除按鈕和它的父李元素,單擊時。這是我的HTML:什麼選擇器用於按鈕的點擊事件

 <div id="empty_message" class="open"> 
      <h3>You have no tasks left to accomplish!</h3> 
     </div> 
     <div id="tasklist"> 
      <ol class="list" id="list"> 
      </ol> 
     </div> 

這是我寫的jQuery的:

$("#add_task").click(function() {    
     //create a li, save input in there, and add to ol 
     var new_task = $('<li></li>'); 
     new_task.text($("#add_todo").val()); 
     //new_task.attr('id', 'new_task'); 
     new_task.appendTo('ol.list'); 

     if (new_task) 
     //create button and attach it to new li element 
     var new_button = $('<input />').addClass('done'); 
     new_button.attr({ 
      type : "button", 
      value : "Task Accomplished!" 
     }); 
     new_button.appendTo(new_task); 

    } 

    $("#add_todo").val("").focus(); 

}); 
//end click event of Add task button 

$('.done[value="Task Accomplished!"]').click(function() { 
    $(function() { 
     alert("This is working."); 
    }); 
    //hide <li> element 
    $(this).parentElement.remove(); 

    //if list is empty, show empty message 
    if ($("#list li").length == 0) 
     $("#empty_message").show(); 

    $("#add_todo").focus(); 
}); 
//end click event of Task Accomplished button 

添加任務按鈕(第一功能)工作。我無法弄清楚爲什麼「任務已完成」按鈕不起作用!誰能幫我嗎?

+0

jQuery的對象沒有一個'parentElement'屬性。 – Xufox

回答

0
$("#add_task").on('click', function() {    
    //create a li, save input in there, and add to ol 
    var new_task = $('<li />', { 
     text : $("#add_todo").val() 
    }); 

    var new_button = $('<input />', { 
     'class' : 'done', 
     type : 'button', 
     value : 'Task Accomplished!', 
     on  : { 
      click : function() { 
       $(this).closest('li').remove(); 
       if ($("#list li").length == 0) { 
        $("#empty_message").show(); 
       } 
       $("#add_todo").focus(); 
      } 
     } 
    }); 

    $('#list').append(new_task.append(new_button)); 
    $("#add_todo").val("").focus(); 
}); 

創建事件處理程序爲您創建的元素,並使用closest代替parentElement

-1

$('.done[value="Task Accomplished!"]').click(function() { 
 
    $(function() { 
 
     alert("This is working."); 
 
    }); 
 
    //hide <li> element 
 
    //$(this).parentElement.remove(); // doesn't work ! 
 
    $(this).closest('li').remove(); 
 
    //if list is empty, show empty message 
 
    if ($("#list li").length == 0) 
 
     $("#empty_message").show(); 
 

 
    $("#add_todo").focus(); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 
<li><input class="done" type="button" value="Task Accomplished!" /></li>