如何在URL中使用变量执行Javascript代码
我真的很少使用Javascript,并且在理解如何使以下方面起作用时遇到了一些麻烦。我的目标是在页面加载时执行特定的Javascript操作,并且添加到URL末尾的变量将触发要执行的JavaScript操作。我正在寻找的页面的URL是http://www.morgantoolandsupply.com/catalog.php。每个由JavaScript驱动的“+ expand”按钮都会下拉页面的某个区域。最终,我希望能够创建一个URL,在页面加载时自动下拉某个类别。有人可以向我解释这个过程吗?预先感谢任何帮助!如何在URL中使用变量执行Javascript代码
您已经有了调用功能:toggle2()
,它采用两个参数,除了最后一个数字外,其他两个参数恰好相同。因此,创建一个包含该号码的网址:http://www.morgantoolandsupply.com/catalog.php#cat=4
然后使用正则表达式在location.hash
中找到该号码。如果您决定在未来使用它们,这个版本足够强大,可以处理多个网址参数:/[\#&]cat=(\d+)/
。但是,如果您希望从不向网址添加其他任何内容,则可以使用简单的/(\d+)/
。
一旦获得了号码,使用该号码创建两个参数并呼叫toggle2()
是一件简单的事情。
这应该工作:
window.onload = function() {
if (/[\#&]cat=(\d+)/.test(location.hash)) {
var cat = parseInt(RegExp.$1);
if (cat > 0 && cat < 13) {
toggle2("toggle"+cat, "displayText"+cat);
}
}
}
这个工作完美!非常感谢你的帮助! – user924650
你必须有点“手动”解析URL,因为在URL中的参数不会自动传递给JavaScript,就像它们在服务器端脚本(通过PHP $_GET
,例如)
一方式是使用URL片段标识符,即最后可以使用的“#something”位。这可能是做这件事,因为碎片不会被发送到服务器的最巧妙的方法,所以它不会与任何其他参数
// window.location.hash is the fragment i.e. "#foo" in "example.com/page?blah=blah#foo"
if(window.location.hash) {
// do something with the value of window.location.hash. First, to get rid of the "#"
// at the beginning, do this;
var value = window.location.hash.replace(/^#/,'');
// then, if for example value is "1", you can call
toggle2('toggle' + value , 'displayText' + value);
}
的URL“HTTP混淆://www.morgantoolandsupply。 com/catalog.php#1“会自动扩展”toggle1“元素。
或者,也可以使用普通的GET参数(即“?富=栏”)
var parameter = window.location.search.match(/\bexpand=([^&]+)/i);
if(parameter && parameter[1]) {
// do something with parameter[1], which is the value of the "expand" parameter
// I.e. if parameter[1] is "1", you could call
toggle2('toggle' + parameter[1] , 'displayText' + parameter[1]);
}
window.location.search
包含参数,即一切从问号端部或所述URL片段。如果给定URL“example.com/page.php?expand=foo”,则parameter[1]
将等于“foo”。所以URL“http://www.morgantoolandsupply.com/catalog.php?expand=1”将扩展“toggle1”元素。
我也许会去寻找一些比URL中的数字更具描述性的东西,例如使用下拉列表的标题(比如“#abrasives”或“expand = abrasives”而不是“#1”或“expand = 1”),但是这需要对现有页面进行一些调整,因此稍后请留下以供后续使用
在碎片中填充额外的东西并查看'window.location.hash'可能对客户端解决方案更好。 –
@ muistooshort:嘿,我正在更新我的回答,准确地提出,当你评论时:) - 我同意,使用片段也是我的首选解决方案。但是当我第一次写回答的时候,我太忙于GET参数了 – Flambino
不是一个完整的答案(“给一个人一条鱼”等等),但您可以从沿着这些线:
// entire URL
var fullURL = window.location.href;
// search string (from "?" onwards in, e.g., "www.test.com?something=123")
var queryString = window.location.search;
if (queryString.indexOf("someParameter") != -1) {
// do something
}
更多信息可从Mozilla开发者网络获得window.location。
话虽如此,鉴于你在谈论一个PHP页面,为什么你不使用一些服务器端PHP来实现相同的结果呢?
谢谢大家帮助我通过这个!我一直在努力寻找一个解决方案好几天,但所有的答案肯定会增加我对这个应该如何工作的理解。 – user924650