在Jquery Ajax响应中使用选择器和$(this)

我想知道如何在Ajax响应中使用Jquery选择器。 我的网站有一个feed,每个主要块都有一个唯一的ID,但我不想单独识别其中的每个div(这很多)。 到目前为止,$(this)从主事件处理程序中返回单击的ID,但是当我在响应函数中使用它时,我得到’undefined’。 如何从响应中获得与$(this)相同的效果,或者我是否必须在某处找到唯一的ID?

主要function是通过具有特定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处理程序中,所以只需执行以下操作:

 $(...).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已经不再是你所期望的了。

在创建回调之前将其当前值保存在变量中有助于:

 var self = this; function (msg) { var container = $(self).parent().attr('id'); alert (container); //returns undefined }