2015-11-22 41 views
0

我正嘗試使用jquery創建一個待辦事項列表,並且希望向我的表中添加一個刪除按鈕。當刪除按鈕顯示在表中時,它只是說[object Object]。有人能幫忙嗎?以下是我的jQuery和HTML。我的jQuery的最後一行是我添加刪除按鈕的地方。在動態表中顯示爲[對象對象]的按鈕

$(document).ready(function() { 
 
    //Add the importance level to the first column of the to do table 
 
    $("#submit-button").on("click", function addTask() { 
 
    var taskToDo = $("#comment").val(); 
 
    var newRow = $("<tr>"); 
 
    var newTd = $("<td>"); 
 
    var deleteBtn = $("<button>").addClass("btn btn-danger").append("X"); 
 

 
    //Append the importance ranking to the table 
 
    if($('#vimp').is(':checked')) 
 
     alert("Your task is very important") 
 
     newRow.append("<td>X</td>"); 
 
     /*var bullet = $("&bull;").css("color","red"); 
 
     $("#to-do-list").append(newRow); 
 
     newRow.append('<td>'+bullet+'</td>');*/ 
 

 
    if($('#simp').is(':checked')) 
 
     alert("Your task is somewhat important") 
 

 
    if($('#canwait').is(':checked')) 
 
     alert("Your task can wait") 
 
    
 
    //Append the task to the table 
 
    $("#to-do-list").append(newRow); 
 
     //newRow.append("<td>X</td>"); 
 
     newRow.append('<td>'+taskToDo+'</td>'); 
 
     newRow.append('<td>'+deleteBtn+'</td>'); 
 

 
    }); 
 

 
});
 <table class="table table-striped table-responsive table-hover" id="col-width"> 
 
     <col width="30px"> 
 
     <col width="400px"> 
 
     <thead> 
 
      <tr> 
 
      <td>Importance</td> 
 
      <td>Task</td> 
 
      <td>Delete button</td> 
 
      </tr> 
 
     </thead> 
 
     <tbody id="to-do-list"> 
 
     </tbody> 
 
     </table>

+0

因爲你是用串聯的字符串對象。嘗試附加刪除按鈕的HTML,或者,嘗試將單元格追加到該行並將該按鈕添加到單元格 –

回答

1

deleteBtn是一個jQuery對象,但操作者+'<td>'+deleteBtn+'</td>'需要字符串,因此該對象被自動轉換爲它的字符串表示。

要解決此問題,需要將td追加第一,然後按鈕添加到td,例如像這樣:

newRow.append('<td>').find('td').last().append(deleteBtn); 
+0

謝謝!我用這種方法的問題是,當我這樣做時,刪除按鈕被添加在空的​​標籤之後,而不是添加到實際的標籤中。我可以使用不同的方法嗎? – wariofan1

+0

@ wariofan1對不起,我的壞。與本地「appendChild」混淆,後者返回附加元素。我已經修復了代碼。 – Teemu