使用 javascript 在 url 中查找参数,然后应用 if then 逻辑
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8190260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
use javascript to find parameter in url and then apply if then logic
提问by rob melino
I am trying to make my page perform an action only if it sees that a particular parameter is present in the url.
我试图让我的页面仅在看到 url 中存在特定参数时才执行操作。
I essentially want the javascript code to do this:
我基本上希望 javascript 代码做到这一点:
consider an example page such as: http://www.example.com?track=yes
考虑一个示例页面,例如:http: //www.example.com?track=yes
If a page loads that contains the parameter 'track' within the url, print 'track exists', else if the 'track' parameter doesn't exist print 'track does not exist'
如果页面加载的 url 中包含参数“track”,则打印“track exists”,否则如果“track”参数不存在,则打印“track does not exist”
回答by deviousdodo
This should work:
这应该有效:
if (window.location.search.indexOf('track=yes') > -1) {
alert('track present');
} else {
alert('track not here');
}
回答by JW8
回答by lonesomeday
It's not hard to split up the query string to find the relevant bits:
拆分查询字符串以找到相关位并不难:
var path = location.substr(1), // remove ?
queryBits = path.split('&'),
parameters = {},
i;
for (i = 0 ; i < queryBits.length ; i++) {
(function() { // restrict keyval to a small scope, don't need it elsewhere
var keyval = queryBits[i].split('=');
parameters[decodeURIComponent(keyval[0])] = decodeURIComponent(keyval[1]);
}());
}
// parameters now holds all the parts of the URL as key-value pairs
if (parameters.track == 'yes') {
alert ('track exists');
} else {
alert ("it doesn't");
}
回答by Chazbot
What you're looking for is called the Query String or Query Parameter. See this function to get it w/o the use of plugins like jQuery: How can I get query string values in JavaScript?
您要查找的内容称为查询字符串或查询参数。请参阅此函数以在不使用 jQuery 等插件的情况下获取它:如何在 JavaScript 中获取查询字符串值?
回答by Ry-
You can use the window.location.search
property:
您可以使用该window.location.search
属性:
if(/(^|&)track(&|$)/.test(window.location.search.substring(1))) {
alert('track exists!');
} else {
alert('it doesn\'t...');
}