2010-09-22 24 views

回答

4

你不需要jQuery對於這一點,只是香草的JavaScript:

var href = someLinkElement.href; 
var lastIndex = href.lastIndexOf('/') + 1; 
var lastComponent = href.substring(lastIndex); 
+2

+1避免正則表達式;-) – Tomalak 2010-09-22 16:05:31

+0

一致認爲jQuery是矯枉過正,直到你有,你想......那麼'$(元素)。每個工作這些事情的清單( ...);'變得非常方便 – jcolebrand 2010-09-22 16:13:27

2
var num = $("a.ajax").attr("href").replace(/.*\/(\d+)$/, "$1"); 

正則表達式的說明:

.*   # anything (this runs right to the end of the string) 
\/   # a slash (backtracks to the last slash in the string) 
(\d+)  # multiple digits (will be saved to group $1) 
$   # end-of-string anchor (ensures correct match) 

replace()通話將取代與整個輸入字符串數字在結尾,不管它是什麼。如果最後沒有號碼,它將返回""

哦,這裏額外的收穫是什麼,使用jQuery的多一些,根據需要修改:

$("a.ajax").each(function() { 
    $(this).data("num", /* store in data for later re-use */ 
    $(this).attr("href").replace(/.*\/(\d+)$/, "$1") 
); 
}); 
+0

你是JEDI。這現在甚至是一個記錄jQuery的方法,它的工作原理。如何不'實際取代任何東西? – Trip 2010-09-22 16:07:42

+0

@Trip:'attr(「href」)'返回一個字符串,基本上是屬性值的一個副本。 'replace()'在該副本上運行。爲了替換實際的'href'值,我需要調用'attr(「href」,newValue)',但這不會發生在這裏。 – Tomalak 2010-09-22 16:13:10

1
$(".ajax").each(function() { 
    var lastElementOfHREF = $(this).attr("href").split("/").pop(); 
    // now you do something here with this lastElement... 
}); 
2

你可以這樣說:

var Value=$("a.ajax").attr("href").split("/").pop(); 

這是比快使用正則表達式。

Example in action.

+0

因爲它是一組畫廊我想象一次會有很多這樣的畫廊。你的只抓住其中一個。只是想我會指出。 〜另外,我喜歡我們如何設法在同一時間發佈大致相同的答案;) – jcolebrand 2010-09-22 16:12:06

+0

OP沒有表明有多個。即「我試圖在** ** href結尾處抓住'15'。 – 2010-09-22 16:15:40

+0

用於split()'/'pop()'方法。這比使用'lastIndexOf()'/'substring()'做更耗費資源,但對於大多數UI代碼來說,這幾乎沒有什麼明顯的區別。 – Tomalak 2010-09-22 16:22:29