2016-07-28 24 views
0

我有一個表格通過重新加載頁面進行更新,我試圖在本地處理。所以我通過PHP渲染下面的表格,然後通過ajax進行更新。當我現在想要刪除行時,我想從ajax獲得成功的響應時刪除行,但我要刪除的代碼是全局的,並且無論如何都會刪除。有什麼辦法讓我在js函數中封裝我的js代碼,並且可能通過onclick事件調用它?根據AJAX調用本地刪除表格行

我的表:

<table> 
<tr> 
    <td>1</td> 
    <td><a class="remove" href='#' onClick="Remove()">Remove</a></td> 
</tr> 
    <tr> 
    <td>2</td> 
    <td><a class="remove" href='#'>Remove</a></td> 
    </tr> 
    <tr> 
    <td>3</td> 
    <td><a class="remove" href='#'>Remove</a></td> 
    </tr> 
</table> 

我去除

$(document).on("click", "a.remove", function() { 
    $(this).closest("tr").remove(); 
}); 

JS而這正是我想在本地刪除tablerow的:

function Remove(id) { 
$.ajax({ 
    url: "ajax/ajax.php", 
    type: "POST", 
    data: { 
operation: "remove", 
id: id 
}, 
    success: function(response){ 
     // This is where I want the deletion to be 
    }, 
    error: function (response) { 
     console.log("Something went wrong"); 
    }, 
}); 
} 

人對如何的想法重做的js刪除工作在Remove()?

回答

1

你的表更改爲

<table> 
<tr> 
    <td>1</td> 
    <td><a class="remove" data-rowid="1">Remove</a></td> 
</tr> 
<tr> 
    <td>2</td> 
    <td><a class="remove" data-rowid="2">Remove</a></td> 
</tr> 
<tr> 
    <td>3</td> 
    <td><a class="remove" data-rowid="3">Remove</a></td> 
</tr> 
</table> 

data-rowid值應該是你要刪除的動態項目ID!

和您的JS-代碼可能是:

$(document).on("click", "a.remove", function(event) { 
    event.preventDefault(); 
    var id = $(this).data("rowid"); 
    var row = $(this).closest("tr");  
    $.ajax({ 
     url: "ajax/ajax.php", 
     type: "POST", 
     data: { 
      operation: "remove", 
      id: id 
     }, 
     success: function(response){ 
      row.remove(); 
     }, 
     error: function (response) { 
      console.log("Something went wrong"); 
     } 
    }); 

}); 
+0

你是一個明星。這完美的作品! – DaveLar

+0

很高興我能幫上忙 –