3 回答
TA贡献1799条经验 获得超6个赞
HTML<input>元素没有innerText属性,请value改用。您还应该删除该按钮并创建一个文本节点,其值为 using createTextNode()。最后在输入元素之后插入创建的文本元素:
function check1() {
const answer = document.getElementById("question1");
const mybutton = document.getElementById("button1");
mybutton.remove();
var textNode;
if(answer.value.trim() == "Seoul"){
textNode = document.createTextNode("CORRECT");
}
else textNode = document.createTextNode("Seoul");
//insert the text node after the answer element
answer.parentNode.insertBefore(textNode, answer.nextSibling);
}
<input id="question1"/>
<input type="button" id="button1" value="See Answer" onclick="check1();">
TA贡献1871条经验 获得超8个赞
输入类型按钮和文本没有innerText,使用 value 代替:
function check1() {
const answer = document.getElementById("question1").innerText;
const mybutton = document.getElementById("button1");
if(answer=="Seoul") {
mybutton.parentNode.removeChild(mybutton);
var t = document.createTextNode("Correct");
document.body.appendChild(t);}
else {
mybutton.parentNode.removeChild(mybutton);
var t = document.createTextNode("Seoul");
document.body.appendChild(t);
}
}
<input type="button" id="button1" value="See Answer" onclick="check1();">
<input id="question1">
TA贡献1906条经验 获得超3个赞
您可以通过 id 获取元素并将类型的setattribute设置为 text 来将按钮字段更改为文本字段
document.getElementById("button1").setAttribute("type","text");
要禁用转换后的文本字段,您可以这样做。
document.getElementById("button1"). disabled = true;
完整代码:
<script type="text/javascript">
function check1() {
//Fetch elements and answers
const answer = document.getElementById("question1").innerText;
const mybutton = document.getElementById("button1");
//Change button to text field with changing its type attriube to text
mybutton.setAttribute("type","text");
//Disable the newly created text field
mybutton.disabled = true;
if(answer === "Seoul"){
mybutton.value = "CORRECT";
}else{
mybutton.value = "Seoul";
}
}
</script>
最后,在进行比较时使用三等号 (===) 而不是双等号 (==)。双等号 (==) 在执行比较之前将变量值转换为相同类型。而三等号 (===) 不进行任何类型转换(强制),并且仅当值和类型相同时才返回 true
添加回答
举报