Using selectors and $(this) in Jquery Ajax response

邮差的信 提交于 2019-12-01 09:09:28

问题


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?

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

      }

回答1:


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



回答2:


Since the ajax is inside the click handler just do this:

$(...).click(function(){
      var $this = $(this); //<-- reference variable
      //ajax function...
      function(msg){ 

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

      }
})



回答3:


I assume you're referring to referencing this in a callback function. You can do something like this:

$('#stuff').click(function() {
    var $this = $(this);
    $.get('...', function() {
        //do stuff with $this
    });
});



回答4:


This is a side-effect of the callback function being invoked asynchronously. When it is called, this is no longer what you expect it to be.

Saving the current value of this in a variable before you create the callback helps:

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


来源:https://stackoverflow.com/questions/6456381/using-selectors-and-this-in-jquery-ajax-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!