2010-08-03 34 views
2

我正在使用簡寫AJAX調用$.get,但是當我嘗試使用$(this)引用變量時,jQuery告訴我它未定義。

這裏是代碼塊:

$('.replaceWithObject').live('click', function(event) { 
    var cid = $(this).find('input').val(); 
    $.get('GetVideoComment.ashx?cid=' + cid, function(data) { 
     $(this).html(data); 
    }); 
}); 

它發現cid就好,如$(this)可用之前$.get。內部.get$(this)未定義。在get之前將變量設置爲$(this)也不起作用?

getVideoComment.ashx?cid=628工作時,它返回一個flash對象。問題在於get內部的$(this)未定義。

關於如何做我想在這裏做的任何想法?或者我做錯了什麼?

回答

4

您需要緩存初始選擇,以便在您的回調觸發時存在。

$('.replaceWithObject').live('click', function(event) { 
    var $this = $(this); 
    var cid = $this.find('input').val(); 
    $.get('GetVideoComment.ashx?cid=' + cid, function(data) { 
     $this.html(data); 
    }); 
}); 
2

試試這個:

$('.replaceWithObject').live('click', function(event) { 
    var that = $(this); 
    var cid = that.find('input').val(); 
    $.get('GetVideoComment.ashx', {'cid': cid}, function(data) { 
     that.html(data); 
    }); 
}); 

的問題是,thisget功能所有的內不再.replaceWithObject 如果緩存此上的click事件,並使用高速緩存,然後它會工作爲你。

2

由於返回的數據似乎是HTML,你也可以只使用load()

加載數據從服務器返回的HTML放入匹配元素。

$('.replaceWithObject').live('click', function(event) { 
    var cid = $(this).find('input').val(); 
    $(this).load('GetVideoComment.ashx?cid=' + cid); 
    // or $(this).load('GetVideoComment.ashx', {cid: cid}); 
}); 
+0

Thanks +1。這是有效的,而且更有意義。但我不明白爲什麼我不在這個範圍之內......但實際上並沒有。 =( – Jason 2010-08-25 14:42:26

+0

@Blankasaurus:'this'是一個特殊的變量,被設置爲對象,方法被調用,你不是在元素上調用'get()',而是調用'jQuery'對象。 'this'不能設置爲元素,因爲它不知道它的任何內容。 – 2010-08-25 15:30:01