0

我正在转换一堆超链接以使用 jQuery 发出简单的 GET 请求。我想this在 Ajax 调用中维护对的引用,我需要使用bind/ live/ 其他东西吗?

$(document).ready(function(){
    $(".mylink").click(function(){
        var url = $(this).attr('href');
        $.get(url,function(data){
            $(this).parent().html(data); // this is now out of scope
        });
        return false;
    });
});
4

4 回答 4

3
$(document).ready(function(){
    $(".moderate").click(function(){
        var $this = $(this);
        var url = $this.attr('href');

        $.get(url,function(data){
            $this.parent().html(data);
        });
        return false;
    });
});

那应该对你有用。

于 2010-01-19T12:39:20.260 回答
1
$(document).ready(function(){
    $(".moderate").click(function(){
        var url = $(this).attr('href');
        var that = $(this);
        $.get(url,function(data){
            that.parent().html(data);
        });
        return false;
    });
});
于 2010-01-19T12:38:38.623 回答
1

您需要保存this到另一个变量,如下所示:

$(document).ready(function(){
    $(".mylink").click(function(){
        var realThis = this;
        var url = $(this).attr('href');
        $.get(url,function(data){
            $(realThis).parent().html(data); // realThis is now in scope
        });
        return false;
    });
});

AJAX 回调可以访问外部方法的变量,因此这种技术可以正常工作。

live如果您想处理所有 .mylink元素,即使是后来添加的元素,您只需要调用。

于 2010-01-19T12:39:40.770 回答
1

范围界定在 javascript 中是一团糟 :)

在 jQuery 1.4 中,您有一个内置的代理函数,可以将作用域带入任何回调,请参阅:http ://api.jquery.com/jQuery.proxy/ 。

但是自己创建一个很容易:

var proxy = function( fn, scope ) {
    if ( typeof fn !== 'function' ) {
        return function() {};
    }
    scope = scope || this;
    return function() {
        return fn.apply( scope, Array.prototype.slice.call(arguments) );
    };
}

$(document).ready(function(){
    $(".moderate").click(function(){
        var url = $(this).attr('href');
        $.get(url, proxy(function(data) {
            $(this).parent().html(data);
        }, this));
        return false;
    });
});

您还可以将范围放在变量中并稍后访问它:

$(document).ready(function(){
    $(".moderate").click(function(){
        var scope = this;
        var url = $(this).attr('href');
        $.get(url, function(data) {
            $(scope).parent().html(data);
        });
        return false;
    });
});
于 2010-01-19T12:41:04.823 回答