我无法在标题中解释自己。我想要的是在斜杠之间获取字符串。像那样: www.example.com/foo/bar/id/1 我想要得到“foo”。因为这些代码是我写的。
select: function(event, ui) {
if(window.location.href = "news/" + ui.item.slug){
window.location.href =null;
}
else
window.location.href ="news/" + ui.item.slug;
}
我有一个自动完成搜索字段。当我点击结果时,它会将我重定向到 www.example.com/news/34523 在此页面中,如果我再次使用搜索字段,它会将我重定向到 www.example.com/news/news/12412 之后我得到 404。但是如果我不在新闻选项卡中,例如 www.example.com /foo 当我使用搜索字段时它工作得很好。我只需要一个 if 语句,如果我在新闻页面中就像另一个页面一样。
您可以简单地使用
location.pathname
属性来获取第一个和第二个斜杠之间的部分,并基于此运行代码。
console.log(window.location.pathname);
console.log(window.location.pathname.split("/")[1] === "foo");
为了证明这是有效的,这里有另一个片段,就好像
url
是 window.location
:
let url = document.createElement('a');
url.href = "http://www.example.com/foo/bar/id/1";
console.log(url.pathname);
console.log(url.pathname.split("/")[1] === "foo");
问题似乎在于您的网址被重定向。尝试下面的代码。
select: function(event, ui) {
if(window.location.href = "/news/" + ui.item.slug){
}
else
window.location.href ="/news/" + ui.item.slug;
}
您可以使用
attr()
方法获取当前 URL:
$(location).attr('href');