如何将$(this)传递给jquery中的.get函数?

Jer*_*ry2 2 jquery get this

我有:

    function dosomething(data) {
    alert($(this).attr('class'))
    $(this).children('img').attr('title', data) 
}

$('.test').bind('mouseover', function() {
    $.get('/inc/ajax-function.asp?action=check', dosomething);

})
Run Code Online (Sandbox Code Playgroud)

现在这显然不起作用.我想做的是:

当调用.get时,将rresult转换为数据(这可行),并将结果放在img的标题中,该标记是您鼠标悬停的链接的子项.如何获得函数的$(this)值?

<a class='test' href='book.asp><img src='image.gif' title='' /></a>
Run Code Online (Sandbox Code Playgroud)

感谢您提供2个好的解决方案.在这种情况下,我不知道哪一个更"更好",更快,更"标准".

Cha*_*ndu 7

您可以使用jQuery代理函数:http://api.jquery.com/jQuery.proxy/

试试这个:

$('.test').bind('mouseover', function() {
    $.get('/inc/ajax-function.asp?action=check', $.proxy(dosomething, this));
})
Run Code Online (Sandbox Code Playgroud)


T.J*_*der 7

使用您已经为mouseover处理程序创建的闭包:

$('.test').bind('mouseover', function() {
    var elm = this;
    $.get('/inc/ajax-function.asp?action=check', function(data) {
        dosomething.call(elm, data);
    });
});
Run Code Online (Sandbox Code Playgroud)

您的get回调将有机会获得的elm地方,然后我们呼吁dosomething通过Function#call(这使得我们传递给第一个参数callthis在调用函数时).(这就是jQuery $.proxy在幕后为你做的事情,创建一个闭包并通过Function#call或者调用函数Function#apply,但是当你有一个闭合的时候,也可以直接使用它.仍然,+1到Chandu,$.proxy是完全没法的这样做的方法.)

或者修改你dosomething的接受元素作为参数,你不必使用Function#call:

function dosomething(elm, data) {
    alert($(elm).attr('class'))
    $(elm).children('img').attr('title', data) 
}

$('.test').bind('mouseover', function() {
    var elm = this;
    $.get('/inc/ajax-function.asp?action=check', function(data) {
        dosomething(elm, data);
    });
});
Run Code Online (Sandbox Code Playgroud)