如何从查询字符串中获取值index.html#id = 1& name = Lionel
设置下面的代码工作?相反#在上面的链接。
示例:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
答案 0 :(得分:0)
那么你的问题就是一个简单的答案。让我们说网址为www.awsomepage.dev?foo=bar&baz#foobar
,命令location.search
将返回?foo=bar&baz
,因为它是search
部分。要访问主题标签数据,您必须使用location.hash
,这将返回#foobar
。
要使代码与#
一起使用,您应该替换
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
通过
var regex = new RegExp("[\\#&]" + name + "=([^&#]*)"),
results = regex.exec(location.hash);
我改变了什么:
第一:在你的正则表达式中,检查?
和&
作为开始。您显然必须将其更改为#
和&
第二:将location.search
更改为location.hash
,因为您要定位哈希值。
希望有所帮助。如需进一步阅读,请在此处重新注释:https://developer.mozilla.org/en-US/docs/Web/API/Window/location