我有一个类似< a href =“/ category / post /?type = 234#content”> link< / a>的锚点。使用jQuery可以在URL中获取“type”的值,并在同一页面中为隐藏的输入类型赋值,而无需刷新页面。
答案 0 :(得分:1)
$(function() {
var val = $('a').attr('href').match(/type\=\d+/)[0].replace(/type\=/,'');
$('input[type=hidden]').val(val);
});
示例:
var href = "/category/post/?type=234#content";
var filter = href.match(/type\=\d+/)[0].replace(/type\=/,'')
console.log(filter);
答案 1 :(得分:0)
我写了一个函数来将查询字符串参数作为地图前一段时间获取:
/**
* Gets the query parameters of the given URI as a associative array or map
* e.g. Given a URI http://www.level3labs.com/jaf?foo=bar&baz=bazzm, will
* give {"foo":"bar", "baz":"bazzm"}
* @param {URI} strUri The uri with a query
* @return Object containing query params or and empty object
*/
function getQueryParams(strUri) {
var paramMap = {};
if(!strUri) {
return paramMap;
}
var strQuery = strUri.substring(strUri.indexOf("?"));
if(strQuery.lastIndexOf("#") !== -1) {
strQuery = strQuery.substring(0, strQuery.lastIndexOf("#"));
}
if(strQuery && strQuery.indexOf("?") === 0 && strQuery.length > 1) {
strQuery = strQuery.substring(1);
var paramValArr = strQuery.split("&");
for(var i = 0, len = paramValArr.length; i < len; i++) {
var paramVal = paramValArr[i];
var delimIdx = paramVal.indexOf("=");
var param = null;
var val = null;
if(delimIdx >= 0) {
param = unescape(paramVal.substring(0, delimIdx));
val = unescape(paramVal.substring(delimIdx + 1));
}else {
param = unescape(paramVal);
}
paramMap[param] = val;
}
}
return paramMap;
}
这可以与下面的代码一起使用:
var uri = $('a').attr('href');
var params = getQueryParams(uri);
$('input[type=hidden]').val(params["type"]));