为什么$(本)AJAX调用后未定义 [英] How come $(this) is undefined after ajax call
问题描述
我在做一个Ajax请求时,一个锚标记被点击一个ID设置为HREF。顺便说一句,这个锚标记是动态创建的。
I am doing an ajax request when an anchor tag is clicked with an ID set to href. Btw, this anchor tag is dynamically created.
<a href="983" class="commentDeleteLink">delete</a>
在锚标记被点击以下code执行:
When the anchor tag is clicked the following code is executed:
$('.commentDeleteLink').live('click', function(event) {
event.preventDefault();
var result = confirm('Proceed?');
if ( result ) {
$.ajax({
url: window.config.AJAX_REQUEST,
type: "POST",
data: { action : 'DELCOMMENT',
comment : $('#commentText').val(),
comment_id : $(this).attr('href') },
success: function(result) {
alert($(this).attr('href'));
//$(this).fadeOut(slow);
}
});
}
});
当我试图显示$(本).attr(HREF),它说这是不确定。我真正想要做的是淡出锚标记,但是当我调查了$ a的值(这)是不确定。
When I tried to display $(this).attr('href') it says it's "undefined". What I really want to do is fadeOut the anchor tag but when I investigated the value of $(this) it is "undefined".
出了什么问题与上面的代码段?
What could be wrong with the snippet above?
推荐答案
您应该尝试
$('.commentDeleteLink').live('click', function(event) {
event.preventDefault();
var result = confirm('Proceed?');
var that = this;
if ( result ) {
$.ajax({
url: window.config.AJAX_REQUEST,
type: "POST",
data: { action : 'DELCOMMENT',
comment : $('#commentText').val(),
comment_id : $(this).attr('href') },
success: function(result) {
alert($(that).attr('href'));
//$(that).fadeOut(slow);
}
});
}
});
由于这
在回调不被点击的元素,你应该缓存这
在变量是
,你可以重新使用,是不理智的情况下
because this
in the callback is not the clicked element, you should cache this
in a variable that
that you can re-use and is not sensible to the context
这篇关于为什么$(本)AJAX调用后未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!