我想知道如何在Ajax响应中使用Jquery选择器。我的站点有一个提要,每个主块都有一个唯一的ID,但我不想唯一地识别其中的每个div(这太多了)。到目前为止,$(this)从主事件处理程序中返回单击的ID,但当我在响应函数中使用它时,我会得到"undefined"。我如何从响应中获得与$(this)相同的效果,或者我必须在某个地方找到一个唯一的ID?
通过具有特定rel属性的超链接调用主函数
function(msg){
var container = $(this).parent().attr('id');
alert (container); //returns undefined
}
由于函数是AJAX回调,因此可以使用上下文设置:
$.ajax({
// ...
context: this,
success: function(msg) {
// Here, 'this' refers to the same object as when ajax() was called.
var containerId = $(this).parent().attr("id");
window.alert(containerId);
}
});
您还可以在容器本身的上下文中调用回调函数:
$.ajax({
// ...
context: $(this).parent().get(0),
success: function(msg) {
// Now, 'this' refers to the container element.
var containerId = $(this).attr("id");
window.alert(containerId);
}
});
由于ajax在点击处理程序中,所以只需执行以下操作:
$(...).click(function(){
var $this = $(this); //<-- reference variable
//ajax function...
function(msg){
var container = $this.parent().attr('id');
alert (container); //returns undefined
}
})
我假设您指的是在回调函数中引用this
。你可以这样做:
$('#stuff').click(function() {
var $this = $(this);
$.get('...', function() {
//do stuff with $this
});
});
这是异步调用回调函数的副作用。当它被调用时,this
不再是您期望的样子。
在创建回调之前,将this
的当前值保存在变量中有助于:
var self = this;
function (msg) {
var container = $(self).parent().attr('id');
alert (container); //returns undefined
}