【发布时间】:2010-09-23 00:17:01
【问题描述】:
我正在尝试使用 jquery 在 href 末尾获取 15。
<a class="ajax" href="/organizations/1/media/galleries/15">Silly Gangs</a>
有什么想法吗?
【问题讨论】:
标签: jquery html css-selectors
我正在尝试使用 jquery 在 href 末尾获取 15。
<a class="ajax" href="/organizations/1/media/galleries/15">Silly Gangs</a>
有什么想法吗?
【问题讨论】:
标签: jquery html css-selectors
你不需要jQuery,只需要普通的 JavaScript:
var href = someLinkElement.href;
var lastIndex = href.lastIndexOf('/') + 1;
var lastComponent = href.substring(lastIndex);
【讨论】:
$(elements).each(...); 变得非常方便
【讨论】:
15”。
split()/pop() 方法。这比使用 lastIndexOf()/substring() 更耗费资源,但对于大多数 UI 代码来说,这几乎不会产生任何明显的差异。
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")
);
});
【讨论】:
attr("href") 返回一个字符串,基本上是属性值的副本。 replace() 对该副本进行操作。要替换实际的 href 值,我需要调用 attr("href", newValue),但这不会发生在这里。
$(".ajax").each( function() {
var lastElementOfHREF = $(this).attr("href").split("/").pop();
// now you do something here with this lastElement...
});
【讨论】: