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
添加回答
举报
