JQuery - $这个没有定义

时间:2011-10-05 16:22:59

标签: jquery

尝试让这段代码正常工作,但我在firebug中遇到的错误是$this is not defined,我不明白为什么

为了解释有关此代码的背景,我有一个具有相同类的跨度列表,因此当我单击特定跨度时,我需要发送ajax请求并更新该特定跨度。

希望这是有道理的。

$(document).ready(function() {

function postAndFade($node, post_key) {
    var id = $node.parents('.id').find('.id-value').text();
    var post_val = $node.text();
    $node.fadeOut('slow');

    $.ajax({
        type: "POST",
        url: "process.php",
        data: "id="+id+"&"+post_key+"="+post_val,
        success: function(data) {
           $node.html(data);
           $node.fadeIn('slow');        
        }
    });
return false;
}
$('.featured-value').click(function() { return postAndFade($this, 'featured'); });
$('.visible-value').click(function() { return postAndFade($this, 'visible'); });
});

5 个答案:

答案 0 :(得分:15)

因为它不是 - 你正在寻找$(this)

富勒解释 - jQuery通过将this的值设置为触发事件的元素来设置事件处理程序的上下文。为了在jQuery中引用它,你需要将它包装在jQuery调用中,如下所示:$(this)。因为你经常需要使用该元素做很多事情,所以将它分配给名为$this的变量是一种常见的编码模式:

$(el).click(function() {
    var $this = $(this);
    // now do stuff with $this
});

但这是一个惯例,而不是jQuery为你做的事情。

答案 1 :(得分:4)

使用此代码

$(this) instead of $this

答案 2 :(得分:2)

您需要$(this),而不是$this

答案 3 :(得分:2)

你想要

$('.featured-value').click(function() { return postAndFade($(this), 'featured'); });
$('.visible-value').click(function() { return postAndFade($(this), 'visible'); });

this是对DOM元素的引用。

$this不是任何东西,它有时像这样使用:var $this = $(this)以保存jQuery对象,因此您不会多次重新创建它。

答案 4 :(得分:2)

尝试使用$(this)而不是$ this

$('.featured-value').click(function() { return postAndFade($(this), 'featured'); });
$('.visible-value').click(function() { return postAndFade($(this), 'visible'); });
相关问题