这是一种不太优雅的实现方式。添加类名很简单。这会将一个 groupname 添加到你的 main id 上,其中 groupname 是群组名称,例如 <section id="main" class="ember-application groupname">。
<script type="text/discourse-plugin" version="0.8">
function getGroupInfo() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
if (myObj.group.name) {
document.getElementById("main").classList.add(myObj.group.name);
}
}
};
var url = window.location.href;
xmlhttp.open("GET", url + ".json", true);
xmlhttp.send();
}
api.onPageChange(() =>{
getGroupInfo();
});
</script>
问题在于,一旦你离开页面,这个类名就会一直保留。我们需要一种方法在离开页面时移除该类名。这可能有更简单的实现方式,但我不太懂 JavaScript,所以想不出更好的办法。希望你能找到更优雅的实现方式,不过这种“笨办法”是把脚本的结尾改为:
api.onPageChange(() =>{
document.getElementById("main").classList.remove("group1");
document.getElementById("main").classList.remove("group2");
document.getElementById("main").classList.remove("group3");
getGroupInfo();
});
这会移除所有可能添加的群组类名。但这看起来确实很笨拙,而且每当你添加新群组时,都需要修改代码。