开发者

Sending $(this) in a callback

开发者 https://www.devze.com 2023-03-12 05:44 出处:网络
I have this jQuery click event $(\'#sidebar .nav a span\').click(function () { var sidebar_nav = $(this);

I have this jQuery click event

$('#sidebar .nav a span').click(function () {
  var sidebar_nav = $(this);
  $("#main").load("type_change.php?id="+id, successCallback);

And then i have the callback to do the binding

var successCallback = function(responseT开发者_如何学运维ext, textStatus, XMLHttpRequest) {
  //doing all the binding in here
}

Is there a way to pass $(this) or sidebar_nav or to the successCallback function so I can do something with it


You could use $.proxy:

$("#main").load("type_change.php?id="+id, $.proxy(successCallback, $(this)));

This will set this inside successCallback to whatever you pass as second parameter.

If you want this still to refer to $("#main"), then you could change the callback to accept one more parameter:

var successCallback = function(responseText, textStatus, XMLHttpRequest, target) {
  //doing all the binding in here
}

and call it like so:

var sidebar_nav = $(this);
$("#main").load("type_change.php?id="+id, function() {
    var args = $.makeArray(arguments);
    args.push(sidebar_nav);
    successCallback.apply(this, args);
});

target will refer to sidebar_nav.


Wrap it in a function, and use .apply() to invoke your function:

$('#sidebar .nav a span').click(function () {
  var sidebar_nav = this;
  $("#main").load("type_change.php?id="+id, function() {
       successCallback.apply( sidebar_nav, arguments );
   });

Now, this in your callback will be the element that was clicked, and the other arguments to the load() callback will be passed along as well.


Another solution would be to generate the callback function and provide this as an argument to the generator:

var genSuccessCallback = function (element) {
  return function(responseText, textStatus, XMLHttpRequest) {
    // use "element" here
  }
}

$("#main").load("type_change.php?id="+id, genSuccessCallback(this));


Is there any reason that you couldn't use an anonymous function in the callback? For instance:

$('#sidebar .nav a span').click(function () {
    var sidebar_nav = $(this);
    main.load("/shop_pos/includes/business_type_change.php?industry_category_id="+industry_category_id+"&business_type_id="+business_type_id+"&class_id="+class_id+"&quantity="+quantity, '', function (responseText, textStatus, XMLHttpRequest) {
        // Function can read sidebar_nav here
        if (textStatus == 'success') {
            // Do stuff here, including that $.post that you might want to do.
        }
    });
0

精彩评论

暂无评论...
验证码 换一张
取 消