高程3使用拼接字符串形式解析的查询字符串,网上有各种正则方式解析的,记得太多,临时需要写的时候,自己都搞混乱了。只记一种吧,用正则。
function getQueryStringArgs() { var search = (location.search.length > 0 ? location.search.slice(1) : ""); var obj = {}; var reg = /([^?&=]+)=([^?&=]*)/g; search.replace(reg, function (match, $1, $2) { var name = decodeURIComponent($1); var val = decodeURIComponent($2); obj[name] = val; return match; }); return obj; }
另外一种方法是
function parseQueryString(url) { var result = {}; var arr = url.split("?"); if (arr.length <= 1) { return result; } else { arr = arr[1].split("&"); arr.forEach(item => { let a = item.split('=') result[a[0]] = a[1] }) return result; } } var url = "http://witmax.cn/index.php?key0=0&key1&key2=2"; var ps = parseQueryString(url); console.log(ps)
这两种方法区别是,对于查询字符串里的key1只有键没有值,方法1会忽略该键,方法2不会忽略而是把值当成undefined
兼容老浏览器的getElementsByClassName,注意这个不适用于多个类名。
function getElementsByClassName(node, classname) { if (node.getElementsByClassName) { return node.getElementsByClassName(classname); } else { var results = []; var elems = node.getElementsByTagName('*'); for (var i = 0; i < elems.length; i++) { if (elems[i].classname.indexOf(classname) != -1) { results[results.length] = elems[i]; } } return results; } }