我有一个'h1'标签,我需要添加一个类来根据url参数更改颜色。我有两个参数传递,这取决于添加不同类的哪一个。
我已经看到@Matt Martin with an answer by @Florian Margaine之前的帖子使用了Switch语句,这看起来像一个不错的方法,我似乎无法让它工作。
我尝试过以下操作但没有成功:
HTML:
<h1 id="head" class="page-head">About Right to Manage for</h1>
jQuery的:
$(function() {
switch (window.location.pathname) {
case '?type=private':
$('#head').addClass('private')
case '?type=retirement':
$('#head').addClass('retirement')
}
});
所以我会有以下任何一种:
<h1 id="head" class="page-head private">About Right to Manage for</h1>
或
<h1 id="head" class="page-head retirement">About Right to Manage for</h1>
答案 0 :(得分:1)
尝试这样做(默认输入路径名):
$(function() {
switch (window.location.pathname) {
case '/about-rtm.php?type=private':
$('#head').addClass('private')
break;
case '/about-rtm.php?type=retirement':
$('#head').addClass('retirement')
break;
default :
$('h1').append(window.location.pathname);
}
});
它会附加在h1
路径名上,以便您查看。 (还console.log())
修改
也许如果没有加载数据,你可以试试这个:
$(document).ready(function(){...});
或
window.onload = function()
{
//your code here
};
编辑#2
let searchParams = new URLSearchParams(window.location.search)
searchParams.has('type') // true
let param = searchParams.get('type') // it could be private or retirement
if(param === 'private'){...}
else if(param === 'retirement'){....}
//or
sitch(param){
case 'private':
.
.
.
}