gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:52:46 28 4
gpt4 key购买 nike

我正在编写一个脚本,该脚本读取文本文件并根据 .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>

我的第一个尝试是向 if/else 函数添加一个“classList.add”,但即使满足“if”条件,它也会将类更改为“red”,因为它已被最后设置。
我是 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);

}

关于JavaScript - 满足 if/elseif 条件时更改类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34879903/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com