3 回答
TA贡献1859条经验 获得超6个赞
在if
声明中,你需要有==
而不是等于。所以在你的情况下它需要是:
if ((generateBtn.innerHTML == "GENERATE")) {
// Change Generate Button to Reset#
let generateBtn = document.getElementById("generateBtn");
generateBtn.addEventListener("click", () => {
if ((generateBtn.innerHTML == "GENERATE")) {
generateBtn.innerHTML = "RESET";
generateBtn.classList.add("resetBtn-shown");
} else {
generateBtn.innerHTML = "GENERATE";
generateBtn.classList.remove("resetBtn-shown");
}
});
.generateBtn-shown {
background-color: red;
color: #eba341;
font-size: 1.5rem;
font-weight: 500;
border-radius: 0.5rem;
width: 10rem;
height: 3rem;
border: none;
}
.resetBtn-shown {
background-color: #21b884;
color: white;
}
<button id="generateBtn" class="generateBtn-shown">GENERATE</button>
TA贡献1824条经验 获得超8个赞
// Change Generate Button to Reset#
let generateBtn = document.getElementById("generateBtn");
generateBtn.addEventListener("click", () => {
if ((generateBtn.innerHTML === "GENERATE")) { //=== instead of =
generateBtn.innerHTML = "RESET";
generateBtn.classList.add("resetBtn-shown");
} else {
generateBtn.innerHTML = "GENERATE";
generateBtn.classList.remove("resetBtn-shown");
}
});
.generateBtn-shown {
background-color: red;
color: #eba341;
font-size: 1.5rem;
font-weight: 500;
border-radius: 0.5rem;
width: 10rem;
height: 3rem;
border: none;
}
.resetBtn-shown {
background-color: #21b884;
color: white;
}
<button id="generateBtn" class="generateBtn-shown">GENERATE</button>
TA贡献1802条经验 获得超5个赞
尝试这个..
你应该使用 textContent 而不是 innerHtml .. 它会给你text来自 html 标签 .. 使用includes方法来比较文本 ..
在谷歌上搜索:innertextvs innerhtmlvs textcontent..
let generateBtn = document.getElementById("generateBtn");
generateBtn.addEventListener("click", (e) => {
if (e.target.textContent.includes("GENERATE")) {
e.target.innerText = "RESET";
e.target.classList.add("resetBtn-shown");
} else {
e.target.innerText = "GENERATE";
e.target.classList.remove("resetBtn-shown");
}
});
.generateBtn-shown {
background-color: red;
color: #eba341;
font-size: 1.5rem;
font-weight: 500;
border-radius: 0.5rem;
width: 10rem;
height: 3rem;
border: none;
}
.resetBtn-shown {
background-color: #21b884;
color: white;
}
<button id="generateBtn" class="generateBtn-shown">GENERATE</button>
添加回答
举报