我需要获取网址,将其拆分为单词并将这些类添加到正文中。
我的网址示例(有时包含?
和#
):
https://example.com/?query_type_cor=or&filtering=1&filter_cor=amarelo&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);
答案 0 :(得分:0)
你走的太长了
首先删除包含它的?|#
之前的网址
使用& | =
分割
对数组中的每个函数使用a并将每个函数添加到body的类列表
var url=window.location.href;
- >这会将当前网址存储到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));