javascript 如何在 jquery 就绪函数中获取 URL 参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3636813/
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
How can I get URL parameter in a jquery ready function?
提问by jini
I have the following:
我有以下几点:
$(document).ready(function() {
window.location.href='http://target.SchoolID/set?text=';
});
So if someone comes to a page with the above mentioned code using a url like:
因此,如果有人使用以下网址访问具有上述代码的页面:
Somepage.php?id=abc123
Somepage.php?id=abc123
I want the text variable in the ready function to read: abc123
我希望就绪函数中的文本变量读取:abc123
Any ideas?
有任何想法吗?
采纳答案by Moin Zaman
you don't need jQuery. you can do this with plain JS
你不需要jQuery。你可以用普通的 JS 做到这一点
function getParameterByName( name ) //courtesy Artem
{
name = name.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");
var regexS = "[\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
and then you can just get the querystring value like this:
然后你可以像这样获取查询字符串值:
alert(getParameterByName('text'));
alert(getParameterByName('text'));
also look here for other ways and plugins: How can I get query string values in JavaScript?
还可以在这里查看其他方法和插件:如何在 JavaScript 中获取查询字符串值?
回答by Patricia
check out the answer to this questions: How can I get query string values in JavaScript?
查看此问题的答案: 如何在 JavaScript 中获取查询字符串值?
that'll give you the value of the id parameter from the query string.
这将为您提供查询字符串中 id 参数的值。
then you can just do something like:
那么你可以做这样的事情:
$(document).ready(function() {
var theId = getParameterByName( id)
var newPath = 'http://target.SchoolID/set?text=' + theId
window.location.href=newPath;
});
回答by ojblass
To help people coming after me that want to have multiple variables and to enhance Moin's answer here is the code for multiple variables:
为了帮助那些想要拥有多个变量的人并增强 Moin 的答案,这里是多个变量的代码:
function getParameterByName( name ) //courtesy Artem
{
name = name.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");
var regexS = "[\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
{
if ((results[1].indexOf('?'))>0)
return decodeURIComponent(results[1].substring(0,results[1].indexOf('?')).replace(/\+/g, " "));
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
}

![javascript 未捕获的异常:[CKEDITOR.editor] 实例已经存在](/res/img/loading.gif)