如何将输入类型更改为Javascript中的文本

我做了一个按钮,但是当我按下按钮时,我想将按钮更改为文本输出。我不想更改按钮内的文本。我想将按钮本身更改为文本。


<input type="button" id="button1" value="See Answer" onclick="check1();">


这是我的按钮。


<script type="text/javascript">

        function check1() {

          const answer = document.getElementById("question1").innerText;

          const mybutton = document.getElementById("button1");

          if(answer=="Seoul") mybutton.innerText = "CORRECT"

          else mybutton.innerText = "Seoul"

        }

      </script>

这是我未完成的版本,如果答案正确,则将按钮更改为文本“正确”,如果答案错误,则将按钮更改为文本“首尔”。


哔哔one
浏览 80回答 3
3回答

哈士奇WWW

HTML<input>元素没有innerText属性,请value改用。您还应该删除该按钮并创建一个文本节点,其值为 using createTextNode()。最后在输入元素之后插入创建的文本元素:function check1() {&nbsp; const answer = document.getElementById("question1");&nbsp; const mybutton = document.getElementById("button1");&nbsp; mybutton.remove();&nbsp; var textNode;&nbsp; if(answer.value.trim() == "Seoul"){&nbsp; &nbsp; textNode = document.createTextNode("CORRECT");&nbsp; }&nbsp; else textNode = document.createTextNode("Seoul");&nbsp; //insert the text node after the answer element&nbsp; answer.parentNode.insertBefore(textNode, answer.nextSibling);}<input id="question1"/><input type="button" id="button1" value="See Answer" onclick="check1();">

ITMISS

输入类型按钮和文本没有innerText,使用 value 代替:function check1() {&nbsp; const answer = document.getElementById("question1").innerText;&nbsp; const mybutton = document.getElementById("button1");&nbsp; if(answer=="Seoul") {&nbsp; &nbsp; &nbsp; &nbsp; mybutton.parentNode.removeChild(mybutton);&nbsp; &nbsp; &nbsp; &nbsp; var t = document.createTextNode("Correct");&nbsp; &nbsp; &nbsp; &nbsp; document.body.appendChild(t);}&nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; mybutton.parentNode.removeChild(mybutton);&nbsp; &nbsp; &nbsp; &nbsp; var t = document.createTextNode("Seoul");&nbsp; &nbsp; &nbsp; &nbsp; document.body.appendChild(t);&nbsp; }}<input type="button" id="button1" value="See Answer" onclick="check1();"><input id="question1">

一只名叫tom的猫

您可以通过 id 获取元素并将类型的setattribute设置为 text 来将按钮字段更改为文本字段document.getElementById("button1").setAttribute("type","text");要禁用转换后的文本字段,您可以这样做。document.getElementById("button1"). disabled = true;完整代码:<script type="text/javascript">function check1() {&nbsp; //Fetch elements and answers&nbsp; const answer = document.getElementById("question1").innerText;&nbsp; const mybutton = document.getElementById("button1");&nbsp; //Change button to text field with changing its type attriube to text&nbsp; mybutton.setAttribute("type","text");&nbsp; //Disable the newly created text field&nbsp; mybutton.disabled = true;&nbsp; if(answer === "Seoul"){&nbsp; &nbsp; mybutton.value = "CORRECT";&nbsp; }else{&nbsp; &nbsp; mybutton.value = "Seoul";&nbsp; }}</script>最后,在进行比较时使用三等号 (===) 而不是双等号 (==)。双等号 (==) 在执行比较之前将变量值转换为相同类型。而三等号 (===) 不进行任何类型转换(强制),并且仅当值和类型相同时才返回 true
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript