3 回答

TA貢獻1865條經驗 獲得超7個贊
您的問題是this回調中的關鍵字是指 window 對象,而不是您期望的 .data 元素。
您可以執行以下操作。
我將元素存儲在外部范圍中以記住單擊的元素,因此我們可以在回調中訪問其數據集。
$('.data').on('click', function(event){
// here im storing the element
// you can probalby also access it with $(this) and store it
const dataEl = event.target
axios.post('ajax/edit_groups/' + dataEl.dataset.id)
.then(function (response){
// in the callback I access the element that is in the outer scope
console.log("in: ", dataEl.dataset.id)
$('#editGroups').modal('show');
$('#id_group').val(response.data_group[0].id);
$('#name').val(response.data_group[0].group_name);
$('#desc').val(response.data_group[0].group_desc);
$('#inputRole').val(response.data_group[0].role);
}).catch(function (error){
console.log(error)
})
}
注意:我沒有測試代碼,它只是為了說明問題可以通過哪種方式解決。
您可能想尋找替代方法。在使用this. _
由于錨標記中有一個元素,因此您需要確保不捕獲它的點擊事件。這與所謂的事件委托有關。
實現這一點的一種簡單方法實際上是使用 CSS。
.data span { pointer-events: none; }
還有其他選擇。

TA貢獻1111條經驗 獲得超0個贊
由于ajax是異步的,所以不能直接調用響應。嘗試在您的函數上添加異步等待,例如:
$('.data').on('click', async function() {
await axios
.post('ajax/edit_groups/' + $(this).attr('data-id'))
.then(function(response) {
console.log('in: ', $(this).attr('data-id'));
$('#editGroups').modal('show');
$('#id_group').val(response.data_group[0].id);
$('#name').val(response.data_group[0].group_name);
$('#desc').val(response.data_group[0].group_desc);
$('#inputRole').val(response.data_group[0].role);
})
.catch(function(error) {
console.log(error);
});
});

TA貢獻1847條經驗 獲得超11個贊
試試這個從 data-id 屬性中獲取 id
console.log("in: ", $(this).dataset.id)
參考 https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes
添加回答
舉報