Jquery $(这个)不工作但$('selector')有效

Joh*_*uki 1 jquery this selector

所以我发送一个ajax请求,如下所示

$('a.new_thumb_update').click(function(e)
{
    e.preventDefault();
    share_id = $(this).attr('share_id');

    $.post('http://studeez.net/resource_layout_files/includes/thumbs_up.php',
    {share_id:share_id},
    function(data)
    {
        alert(data);
        $(this).parent().parent().find('div.thumbs_up').hide();
    });
});
Run Code Online (Sandbox Code Playgroud)

代码与回调函数一样好,我得到警报反馈.

$(this).parent().parent().find('div.thumbs_up').hide();
Run Code Online (Sandbox Code Playgroud)

如果我用实际元素替换$(this),它就可以工作.如下所示

$('a.new_thumb_update').parent().parent().find('div.thumbs_up').hide();
Run Code Online (Sandbox Code Playgroud)

pal*_*aѕн 5

你需要在$(this)这里缓存:

$('a.new_thumb_update').click(function (e) {
    e.preventDefault();
    var $self = $(this);
    share_id = $self.attr('share_id');

    $.post('http://studeez.net/resource_layout_files/includes/thumbs_up.php', {
        share_id: share_id
    }, function (data) {
        alert(data);
        $self.parent().parent().find('div.thumbs_up').hide();
    });
});
Run Code Online (Sandbox Code Playgroud)

因为$(this)在jQuery ajax $.post方法中无法访问.