HTML 按钮在 onclick() 事件后消失

html button disappears after onclick() event

本文关键字:事件 消失 按钮 onclick HTML      更新时间:2023-09-26

大家好,我是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 。

Document.write 函数在调用时会覆盖文档内容,如 Mozilla 开发者网络所述:

注意:当 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>