我正在尝试在AJAX调用之后删除div,但是book.xml
函数似乎无法正常工作。据我了解,它一直爬到找到匹配的地方。
<book>
<creators>
<creator>
<creatorName>Fosmire, Michael</creatorName>
<givenName>Michael</givenName>
<familyName>Fosmire</familyName>
</creator>
<creator>
<creatorName>Wertz, Ruth</creatorName>
<givenName>Ruth</givenName>
<familyName>Wertz</familyName>
</creator>
<creator>
<creatorName>Purzer, Senay</creatorName>
<givenName>Senay</givenName>
<familyName>Purzer</familyName>
</creator>
</creators>
<titles>
<title>Critical Engineering Literacy Test (CELT)</title>
</titles>
</book>
.closest()
答案 0 :(得分:1)
this
的上下文在callback
函数中发生了变化,因此您需要对其进行缓存。
$('#deleteCommentForm').on('submit', function(e) {
e.preventDefault();
let $this = $(this); // <-- Add this code.
let action = $this.attr('action'); // <-- Update here.
axios.delete(action, []).then(function(response) {
$this.closest('div.comment').remove(); // <-- Update here.
});
});
因此,每当启动新功能时,上下文始终会更改。要引用父上下文,请在该范围内定义一个变量。
答案 1 :(得分:1)
您可能在ajax回调函数中丢失了“ this”值。您可以将功能替换为箭头功能
axios.delete(action, []).then(response => {
$(this).closest('div.comment').remove();
});
答案 2 :(得分:0)
ajax响应中的范围不是您正在等待的范围
$('#deleteCommentForm').on('submit', function(e) {
// stop all bubbling of the event
e.preventDefault();
e.stopPropagination();
e.stopImmediatePropagation();
let action = $(this).attr('action');
// first way - using lamda function decoration does not change your scope on this
axios.delete(action, []).then((response) => {
$(this).closest('div.comment').remove();
});
// second Way -- store this to an accessable variable
let element = this;
axios.delete(action, []).then(function(response) {
$(element).closest('div.comment').remove();
});
});