我試圖搶在15
使用jQuery將href ..jQuery如何選擇路徑末尾的數字?
<a class="ajax" href="/organizations/1/media/galleries/15">Silly Gangs</a>
任何想法的結束?
我試圖搶在15
使用jQuery將href ..jQuery如何選擇路徑末尾的數字?
<a class="ajax" href="/organizations/1/media/galleries/15">Silly Gangs</a>
任何想法的結束?
你不需要jQuery
對於這一點,只是香草的JavaScript:
var href = someLinkElement.href;
var lastIndex = href.lastIndexOf('/') + 1;
var lastComponent = href.substring(lastIndex);
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")
);
});
$(".ajax").each(function() {
var lastElementOfHREF = $(this).attr("href").split("/").pop();
// now you do something here with this lastElement...
});
因爲它是一組畫廊我想象一次會有很多這樣的畫廊。你的只抓住其中一個。只是想我會指出。 〜另外,我喜歡我們如何設法在同一時間發佈大致相同的答案;) – jcolebrand 2010-09-22 16:12:06
OP沒有表明有多個。即「我試圖在** ** href結尾處抓住'15'。 – 2010-09-22 16:15:40
用於split()'/'pop()'方法。這比使用'lastIndexOf()'/'substring()'做更耗費資源,但對於大多數UI代碼來說,這幾乎沒有什麼明顯的區別。 – Tomalak 2010-09-22 16:22:29
+1避免正則表達式;-) – Tomalak 2010-09-22 16:05:31
一致認爲jQuery是矯枉過正,直到你有,你想......那麼'$(元素)。每個工作這些事情的清單( ...);'變得非常方便 – jcolebrand 2010-09-22 16:13:27