2017-04-21 52 views
0

我從ajax響應獲取表格數據作爲json。
有些json數據沒有顯示,但我希望它在一個按鈕上點擊以實現其他目的。我該如何得到它?請幫助我。如何在點擊按鈕時獲得ajax響應

function leaveTable() { 
    for (var i = 0; i < leaveList.length; i++) { 
     var tab = '<tr id="' + i + '"><td>' + (i + 1) + '</td><td class="appliedOn">' + leaveList[i].appliedOn + '</td><td class="levType" >' + leaveList[i].levType + '</td><td class="leaveOn" >' + leaveList[i].leaveOn + '</td><td class="duration">' + leaveList[i].duration + '</td><td class="status">' + leaveList[i].status + '</td><td class="approvedOn">' + leaveList[i].approvedOn + '</td><td class="approvedBy">' + leaveList[i].approvedBy + '</td><td><i class="btn dltLev fa fa-times" onclick="cancelLeave(this)" data-dismiss="modal" value="Cancelled"></i></td><tr>'; 

     $('#levListTable').append(tab) 
    } 
} 

從Ajax響應我想leaveTypeId並把它傳遞到sendCancelReq()功能。
完整代碼:https://jsfiddle.net/tytzuckz/18/

回答

1

確切地知道你想要什麼很複雜。我希望這可以幫助你:

首先,我會改變,是而不是在您的html代碼var tab = ...中產生JavaScript事件。我認爲,當你在創建新的dom元素之後添加事件時,它更加清晰易讀。例如:

var tab = $('<tr id="' + i + '">' + 
    '<td>' + (i + 1) + '</td>' + 
    '<td class="appliedOn">' + leaveList[i].appliedOn + '</td>' + 
    '<td class="levType" >' + leaveList[i].levType + '</td>' + 
    '<td class="leaveOn" >' + leaveList[i].leaveOn + '</td>' + 
    '<td class="duration">' + leaveList[i].duration + '</td>' + 
    '<td class="status">' + leaveList[i].status + '</td>' + 
    '<td class="approvedOn">' + leaveList[i].approvedOn + '</td>' + 
    '<td class="approvedBy">' + leaveList[i].approvedBy + '</td>' + 
    '<td><i class="btn dltLev fa fa-times" data-dismiss="modal" value="Cancelled"></i></td>' + 
    '<tr>'); 
$(tab).find('.btn.dltLev').click(function() { cancelLeave(this); }); 

然後,您可以更清楚地把你需要的信息,例如:

而不是上次的代碼

$(tab).find('.btn.dltLev').click(function() { cancelLeave(this); }); 

你可以寫

$(tab).find('.btn.dltLev').click(function() { cancelLeave(this, leaveList[i].leaveTypeId); }); 

並將您的方法cancelLeave擴展爲:

function cancelLeave(elem, leaveTypeId) { 
    var id = $(elem).closest('tr').attr('id') 
    alert(id) 
    $("#cancelLeave").modal("show"); 
    $('.sendCancelReq').val(id); 
    sendCancelReq(leaveTypeId); 

}

0

得到解決
請檢查:https://jsfiddle.net/tytzuckz/19/

function cancelLeave(elem) { 
    var levTypeId = $(elem).attr('id') 
    var id = $(elem).closest('tr').attr('id') 
    $('.currentLevTypeId').val(levTypeId); 
    $("#cancelLeave").modal("show"); 
    $('.sendCancelReq').val(id); 

    } 
    function sendCancelReq() { 

    var a= $('.currentLevTypeId').val(); 
    alert(a) 
}