2012-08-12 68 views
0

我對jQuery非常陌生,並且正在jQuery中創建一個歷史API API腳本,因此只有在新頁面中需要的信息纔會加載點擊。問題是我不知道如何將var放置在處理程序中,至少我認爲它被稱爲處理程序。這絕對是一件簡單的事情。處理程序中的jQuery變量

$("a#click").click(function() { 
var addressValue = $(this).attr("href"); 

    $("#main").load("addressValue #load"); 

return false; 
}); 

回答

3

如果你使用:

$("a#click").click(function() { 
var addressValue = this.href; 

    $("#main").load(addressValue + " #load"); 

return false; 
}); 

它應該工作;問題在於您將變量放入字符串中,因此它將作爲變量名稱進行評估,而不是與' #load'字符串串聯的變量。

另外,對於href,避免調用jQuery稍微快一點,並且只使用本地DOM方法(這是一種微型優化,但它稍微便宜一些)。

值得注意的是,this.href確實(有時 - 問題地)檢索絕對路徑暗示的絕對路徑,嚴格來說,包括域在內的href屬性。而jQuery的方法只是檢索屬性中的任何內容,所以:

<a href="/help/contact.html">contact page</a>: 
this.href   : "http://subdomain.example.com/help/contact.html" 
$(this).attr('href') : "/help/contact.html" 
+0

這兩個正確,謝謝。我將不得不接受@adeneo的答案,因爲他在你之前得到答案 – 2012-08-12 15:53:46

+0

沒問題。很高興有幫助,即使他幫助更快...... =) – 2012-08-12 15:54:48

+0

+1的詳細答案。 – undefined 2012-08-12 15:56:34

1
$("a#click").on('click', function() { 
    var addressValue = $(this).attr("href"); 
    $("#main").load(addressValue+" #load"); 
    return false; 
});