2011-10-05 46 views
2

试图让这段代码工作,但我的萤火得到的错误是$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'); }); 
}); 
+1

我不说话了jQuery,但它真的有所谓的“$这个”东西吗?也许你的意思是'这个'或'$(this)'? –

+1

你确定这是导致错误的代码块吗? – kand

回答

13

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

富勒解释 - jQuery的通过的this值设置为所述元件触发事件设置的事件处理程序的情况下。为了在jQuery中引用它,您需要将其封装在一个jQuery调用中,如下所示:$(this)。因为你经常需要做很多的东西与元素,这是一个常见的编码方式将其分配到一个名为$this变量:

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

但是,这是一个惯例,不是jQuery不会给你的。

+1

aaaaaaaaaaaah。非常感谢你。另一个痛苦的教训。 – martincarlin87

3

使用此代码

$(this) instead of $this 
2

你想$(this),不$this

2

你想

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

this是对DOM元素的引用。

$this不是什么,它有时会像这样使用:var $this = $(this)为了保存jQuery对象,所以你不会多次重新创建它。

2

尝试使用$(本),而不是$这

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