在Jquery Ajax响应中使用选择器和$(this) [英] Using selectors and $(this) in Jquery Ajax response

查看:164
本文介绍了在Jquery Ajax响应中使用选择器和$(this)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在Ajax响应中使用Jquery选择器。我的网站有一个饲料,每个主块有一个唯一的ID,但我不想唯一的ID每个div在那里(这是alot)。到目前为止,$(this)从主事件处理程序中返回点击的ID,但是当我在响应函数中使用它时,我得到'undefined'。如何在响应内部实现与$(this)相同的效果,或者我必须在某处找到唯一的ID?

I am wondering how I use Jquery selectors within the Ajax response. My site has a feed and each main block has a unique ID, but I dont want to uniquly ID every div thats within that (which is alot). So far $(this) returns the clicked ID from within the main event handler, but when I use it within the response function, I get 'undefined'. How can I achieve the same effect as $(this) from within the response or do I have to find a unique ID somewhere?

主函数通过具有特定rel属性的超链接

The main function is being called via a hyperlink with a specific rel attribute

     function(msg){ 

      var container = $(this).parent().attr('id');   
      alert (container); //returns undefined

      }


推荐答案

p>由于该函数是AJAX回调,因此您可以使用上下文设置:

Since the function is an AJAX callback, you can use the context setting:

$.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);
    }
});

您也可以在容器本身的上下文中调用回调函数:

You can also have the callback function called in the context of the container itself:

$.ajax({
    // ...
    context: $(this).parent().get(0),
    success: function(msg) {
        // Now, 'this' refers to the container element.
        var containerId = $(this).attr("id");
        window.alert(containerId);
    }
});

这篇关于在Jquery Ajax响应中使用选择器和$(this)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆