因此,我有以下脚本:
<script>
var id = window.location.href
var buttonText = id.substr(id.lastIndexOf('/') + 1);
jQuery("#first_button").html(buttonText)
</script>
因此,它所做的就是将"id=first_button
“按钮的文本替换为最后一个"/
”旁边的url。
以下是我的站点的网址设置:mysite.com/first/second/
问题是,我所有的页面都以"/
“(前)结尾。网站/什么/)。
所以,在最后一个"/
“之后什么也没有出现。
以下是我正在努力实现的基本目标。
我有两个按钮:First button
和Second Button
。
任何页面的URl都将采用相同的格式:`.com/first/second/。
我试图将first button
替换为/first/
URL,second button
替换为/second/
URL,如下所示。
总之,我现在拥有的代码只会在最后一个"/
“之后通过URL更改第一个按钮文本。
我希望第一和第二个"/
“(如".com/first/
")之间的URL替换第一个按钮标题。
我希望第二个和第三个"/
“(如”.com/first/second/
“)之间的URL替换第二个按钮。
在jQuery中,如何针对特定的URL部分?
谢谢邦奇!
发布于 2015-05-29 22:49:46
你似乎想要这样:
var parts = window.location.href.split('/').filter(Boolean);
jQuery("#second_button").html(parts.pop());
jQuery("#first_button").html(parts.pop());
split('/')
从href生成一个数组,pop()
接受该数组的最后一个元素。
您还可以使用正则表达式来完成这一任务:
var m = window.location.href.match(/([^\/]+)\/([^\/]+)\/?$/);
if (m) {
jQuery("#first_button").html(m[1]);
jQuery("#second_button").html(m[2]);
}
如果您不需要href的最后两个部分,而是路径的前两个部分,请这样做:
var m = window.location.pathname.match(/([^\/]+)\/([^\/]+)/);
if (m) {
jQuery("#first_button").html(m[1]);
jQuery("#second_button").html(m[2]);
}
https://stackoverflow.com/questions/30543203
复制相似问题