如何将url特定参数转换为数组?我使用了很多类型或参数。我尝试使用var types = ['A', 'C'];
下面的代码及其工作。
但它没有使用网址。我需要从URL获取community
参数。如何将url参数转换为数组?像这样var types = ['business_center','wireless_access'];
http://demo/apartments/?price-min=200&price-max=2356&bedroom=3&bathroom=2&ap_features%5B%5D=washer+%26+dryer+connections&ap_features%5B%5D=dishwasher&community%5B%5D=business_center&community%5B%5D=clubhouse&community%5B%5D=covered_parking&submit=SEARCH
//var types = ['A', 'C'];
var i = document.location.href.lastIndexOf('?');
document.location.href.substr(i+1).replace(/community=/g,'').split('&');
$('input[name="community[]"]').prop('checked', function() {
return $.inArray(this.value, types) !== -1;
});
答案 0 :(得分:1)
您可以拆分URL并从中创建一个JSON对象。 参数将成为键,它们的值将存储在相应的数组中。
var url = 'http://demo/apartments/?price-min=200&price-max=2356&bedroom=3&bathroom=2&ap_features%5B%5D=washer+%26+dryer+connections&ap_features%5B%5D=dishwasher&community%5B%5D=business_center&community%5B%5D=clubhouse&community%5B%5D=covered_parking&submit=SEARCH';
var ob = URLToArray(url);
console.log(ob); //output the whole key-value pair object
console.log(ob["community"]); //obtain the "community" values (Array)
function URLToArray(url) {
var request = {};
var pairs = url.substring(url.indexOf('?') + 1).split('&');
for (var i = 0; i < pairs.length; i++) {
if (!pairs[i]) //if empty parameter then continue to next
continue;
var pair = pairs[i].split('='); //split to separate values
if (pair[0].indexOf('%') > -1) //community has some string attached to it starting with %, this cleans it
pair[0] = pair[0].substring(0, (pair[0].indexOf('%')));
var key = pair[0];
if (key in request) //check if any value with same key is already stored
request[key].push(pair[1]); //append to the array of already existing values
else
request[key] = [pair[1]]; //else make a new key-value pair, value is an array of elements
}
return request;
}
&#13;
答案 1 :(得分:0)
您可以使用var url = '?price-min=200&price-max=2356&bedroom=3&bathroom=2&ap_features%5B%5D=washer+%26+dryer+connections&ap_features%5B%5D=dishwasher&community%5B%5D=business_center&community%5B%5D=clubhouse&community%5B%5D=covered_parking&submit=SEARCH';
var final = url.replace('?','').split('&').map(x=> x.split('=')[1]);
console.log(final);
获取查询字符串。然后使用此代码段获取所有查询字符串值。因此,使用此结果数组,您可以过滤或类似您想要的。这是你要找的?
.trapezoid {
height: 100px;
width: 200px;
background:
linear-gradient(to bottom left,white 50%,transparent 52%) 100% 0/40px 100% no-repeat,
linear-gradient(to bottom right,white 50%,transparent 52%) 0 0/40px 100% no-repeat,
linear-gradient(red, yellow);
}
&#13;