[英]Jquery - Split Url and add class to body
我需要获取url,将其拆分为单词并将这些类添加到body中。 我的网址示例(有时会包含?
和#
): https ://example.com/ ?
query_type_cor = or ?
filter = 1& filter_cor = aamarelo ?
filter_estilo = polo ?
filter_tamanho =gg
我希望所有单词都有正文中的类: query_type
or
filtering
1
filter_cor
amarelo
filter_estilo
polo
filter_tamanho
gg
我试过了:
$(window).on('hashchange', function(e){
$('body').
});
而且我把这件衣服堆放在一起,但它并没有分开。
function updateBodyClasses() {
var classNames = [];
// Use `.split()` to separate each key/value pair in the query by `&`
window.location.search.split('&')
// and loop over the results
.forEach(function(c) {
// Now split each pair by '='
var pair = c.split['='];
// Add the value to the left of the '='
if (pair.length > 0) {
classNames.push(pair[0]);
// if there are values on the right of the '='...
if (pair.length > 1) {
// ... split them by ',' and loop through them
pair[1].split(',').forEach(function(t) {
classNames.push(t);
});
}
}
});
// Now append those classNames to the body
$('body').addClass(classNames.join(' '));
}
// If your ajax plugin modifies the url via HTML5 history api...
$(window).on('popstate', updateBodyClasses);
// Update classes on page load
$(window).on('load', updateBodyClasses);
// If the ajax plugin modifies the url using window.location.replace()
// you'll need to check on an interval whether things have changed
// and update accordingly. the following example does this every 1000 milliseconds (or every second)
setInterval(updateBodyClasses, 1000);
你走得太久了
首先删除url直到?|#
包括它。
使用& | =
拆分 & | =
对数组中的每个函数使用a并将每个函数添加到body的类列表中
var url=window.location.href;
- >这会将当前url存储到url
url=url.replace(/[^?#]*[?#]/,'');
- >这会删除之前的部分?|#
包括它
url=url.split(/[&=]/);
- >这会将它拆分为& | =
& | =
它的结果是一个数组
url.forEach(x => document.body.classList.add(x));
- >将所有条目添加到正文的班级列表中
var url=window.location.href; url=url.replace(/[^?#]*[?#]/,''); url=url.split(/[&=]/); url.forEach(x => document.body.classList.add(x));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.