簡體   English   中英

html按鈕在onclick()事件后消失

[英]html button disappears after onclick() event

大家好,我是javascript的新手,我想知道為什么html按鈕在我單擊后就消失了。 瀏覽器顯示文本,但按鈕消失。 這是我的HTML看起來像

<html>
    <head>
        <script type="text/javascript">
            function funcname(){
                document.write("<br/>  <br/> <br/> some text");
            }
         </script>
    </head>
    <body>
        <form>
            <input type="button" name="something" value="touch me" onclick="funcname()"> 
        </form>
    </body>
</html>

write()方法將HTML表達式或JavaScript代碼寫入文檔。

write()方法主要用於測試:如果在完全加載HTML文檔后使用它,它將刪除所有現有的HTML。

答案來自: 來源

   <html>
   <head>
   <script type="text/javascript">

   function funcname()
   {

       document.body.innerHTML += "Some Text";
   }

   </script>
   </head>
   <body>

   <form>
   <input type="button" name="something" value="touch me" onclick="funcname()"> 
   </form>

   </body>
   </html>

嘗試上面的代碼可以正常工作。如果使用document.write()覆蓋主體,則應使用document.body.innerHTML。

如Mozilla開發人員網絡所述,Document.write函數在調用時會覆蓋文檔內容:

注意:當document.write寫入文檔流時,在關閉的(加載的)文檔上調用document.write會自動調用document.open,這將清除文檔。

來源: https : //developer.mozilla.org/en-US/docs/Web/API/Document/write

document.write()將覆蓋您的整個body元素。 如果只想覆蓋特定的部分,則可以定義一個目標並使用innerHTML更改文本。

<html>
    <head>
        <script type="text/javascript">
            function funcname(){
                document.getElementById("someParagraph").innerHTML = "Paragraph changed!";
            }
        </script>
    </head>
    <body>
        <form>
            <input type="button" name="something" value="touch me" onclick="funcname()"> 
        </form>
        <p id="someParagraph">Hey<p>

    </body>
</html> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM