JavaScript - 当满足 if/ elseif 条件时更改类

JavaScript - Change class when if/ elseif condition is fulfilled

本文关键字:条件 elseif 满足 if JavaScript      更新时间:2023-09-26

我正在开发一个脚本,该脚本读取文本文件并根据.txt文件的内容更改div中的文本。
但这不是我的问题。我不想要纯文本,背景颜色应该根据满足 if/elseif/else 函数的条件而变化。

var client = new XMLHttpRequest();	
client.open('GET', 'text.txt');
client.onreadystatechange = function checktxt() {
   if(client.responseText =='not') 
	{
	document.getElementById("response").innerHTML="Connect is working";
	var boxgreen = document.querySelector("#response");
	boxgreen.classList.add("green");
	} 
	else if (client.responseText =='younger') 
	{
	document.getElementById("response").innerHTML="Connect is working";
    var boxgreen = document.querySelector("#response");
	boxgreen.classList.add("green");
	} 
	else 
	{
	document.getElementById("response").innerHTML="Connect isn't working!";
	var boxred = document.querySelector("#response");
	boxred.classList.add("red");
	}
}
client.send();
.green {
   width: 140px; 
   height: 140px; 
   background: #68B267;
   color: white;
}
.red {
   width: 140px; 
   height: 140px; 
   background: #ec4f3e;
   color: white;
}
<div id="response"></div>

我的第一次尝试是将"classList.add"添加到 if/else 函数中,但即使满足"if"条件,它也会将类更改为"红色",因为它已经最终设置好了。
我对javascript很陌生,没有ajax或jquery的经验,但也许这就是我正在寻找的。

如果代码已经运行,则需要删除已添加的类。 client.onreadystatechange = function checktxt() {

使用您的代码,您只需调用

boxgreen.classList.remove("red");  //or green for the other case

并且比它将起作用。

或者,您可以使用切换和简化代码,这样您就不会一遍又一遍地使用相同的行。

client.onreadystatechange = function() {
  var isValid = client.responseText == 'not' || client.responseText == 'younger',
      text = isValid ? "Connect is working" : "Connect isn't working!",
      box = document.querySelector("#response");
  box.innerHTML = text;
  box.classList.toggle("green", isValid);
  box.classList.toggle("red", !isValid);
}