2011-10-05 49 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'); });