根据 URL 字符串中的变量填充属性值
假设我在我的网站上的一个页面上: http://www.example.com /SearchResults.asp?Search=stackoverflow。是否可以使用 JavaScript 或 jQuery 代码从 URL 字符串中获取变量“search”并将其填充到搜索框的值中?
基本上,我将拥有常规识别的搜索框:
<input type="text" title="Search" id="search_box" />
用户将搜索某些内容,但我需要 JavaScript 或 jQuery 代码,当客户进行搜索时,该代码将从 URL 字符串中的“搜索”变量获取值.asp 页面并将其作为“值”添加到 input#search
中。
因此,用户将在此页面上: http://www.example.com/SearchResults。 asp?Search=stackoverflow 搜索框将如下所示:
<input type="text" title="Search" id="search_box" value="stackoverflow" />
谢谢
Let's say I'm on a page on my website: http://www.example.com/SearchResults.asp?Search=stackoverflow. Is it possible to use a JavaScript or jQuery code to get the variable "search" from the URL string and populate it into the value of the search box?
Basically I'll have my regular identified search box:
<input type="text" title="Search" id="search_box" />
And a user will search for something, but I will want a JavaScript or jQuery code that will get the value from the "search" variable in the URL string when the customer is on the Search.asp page and add it as the "value" to the input#search
.
So the user will be on this page: http://www.example.com/SearchResults.asp?Search=stackoverflow and the search box will look like:
<input type="text" title="Search" id="search_box" value="stackoverflow" />
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以尝试这个函数:
如果您上面提到的示例中存在此函数,那么您只需调用 getSearchVariable("Search") 即可返回“stackoverflow”。
因此,在您的页面中,您将有一个如下所示的脚本元素:
希望有帮助!
You could try this function:
If this function is present in the sample you mentioned above, all you would call getSearchVariable("Search") to have "stackoverflow" returned.
So in your page, you would have a script element that looks like:
Hope that helps!
您可以使用 JQuery URI 插件(真正由您无耻地编写)来提取 URL 的任何部分:具体来说,
$.uri(window.location.href).at("query").search
会为所述 URL 生成“stackoverflow”。总体流程是注册一个回调(在页面加载时触发)来分析 URL 并设置该表单元素的值,即:
You can use the JQuery URI plugin (shamelessly written by yours truly) to extract any piece of the URL: Specifically,
$.uri(window.location.href).at("query").search
yields "stackoverflow" for the said URL.The overall flow would be to register a callback (fired on page-load) to analyze the URL and set the value of that form element, that is:
JavaScript
jsFiddle。
用
[]
包装它意味着如果找不到该值,它将返回一个空字符串而不是undefined
(它将被设置为输入的值
并显示为undefined
字符串)。jQuery
jsFiddle。
(/* get GET param */ || [])
的作用是,如果未找到 GET 参数,代码不会出错。JavaScript
jsFiddle.
The wrapping it with
[]
means that if the value was not found, it will return an empty string instead ofundefined
(which would be set to the input'svalue
and shown as theundefined
string).jQuery
jsFiddle.
The
(/* get GET param */ || [])
is so the code will not error if the GET param was not found.