Hea*_*hot 3 javascript url jquery
我有这样的链接:
http://localhost:8162/UI/Link2.aspx?txt_temp=123abc
Run Code Online (Sandbox Code Playgroud)
我想得到价值123abc.我已经按照这个如何在JavaScript中获取查询字符串值?和
jquery从URL获取查询字符串
$(document).ready(function () {
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
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, " "));
}
onload = function () {
alert(getParameterByName('txt_temp'));
alert(getUrlVars()["txt_temp"]);
}
});
Run Code Online (Sandbox Code Playgroud)
但它不起作用.
假设您有许多参数的URL,例如: -
"http://localhost:8162/UI/Link2.aspx?txt_temp=123abc&a=1&b=2"
Run Code Online (Sandbox Code Playgroud)
然后在js你可以这样做:
var url = "http://localhost:8162/UI/Link2.aspx?txt_temp=123abc&a=1&b=2"
Run Code Online (Sandbox Code Playgroud)
要么
var url = window.location.href
Run Code Online (Sandbox Code Playgroud)
然后拆分主URL如:
hashes = url.split("?")[1]
Run Code Online (Sandbox Code Playgroud)
//哈希保存此输出"txt_temp = 123abc&a = 1&b = 2"
然后你可以用&拆分来获得个人参数
编辑
检查此示例:
function getUrlVars() {
var url = "http://localhost:8162/UI/Link2.aspx?txt_temp=123abc&a=1&b=2";
var vars = {};
var hashes = url.split("?")[1];
var hash = hashes.split('&');
for (var i = 0; i < hash.length; i++) {
params=hash[i].split("=");
vars[params[0]] = params[1];
}
return vars;
}
Run Code Online (Sandbox Code Playgroud)
产量
getUrlVars()
Object {txt_temp: "123abc", a: "1", b: "2"}
Run Code Online (Sandbox Code Playgroud)
小智 5
它不起作用,因为您正在运行 内部的函数onload,而该函数不会在 内部触发document.ready,因为当document.ready执行内部的代码时,onload已经触发了。只需从事件中获取您的代码即可onload:
http://jsfiddle.net/whp9hnsk/1/
$(document).ready(function() {
// Remove this, this is only for testing.
history.pushState(null, null, '/UI/Link2.aspx?txt_temp=123abc');
function getUrlVars() {
var vars = [],
hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
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, " "));
}
// You may also place this inside of a function,
// and execute it when you desire, but `onload` is not going
// to fire by itself, when inside of document.ready
alert(getParameterByName('txt_temp'));
alert(getUrlVars()["txt_temp"]);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19420 次 |
| 最近记录: |