[英]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.