简体   繁体   English

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

[英]html button disappears after onclick() event

Hello guys I am New to javascript I want to know why does the html button disappears as soon as i click it. 大家好,我是javascript的新手,我想知道为什么html按钮在我单击后就消失了。 The browser shows the text but the button disappears. 浏览器显示文本,但按钮消失。 here is how my html looks likes 这是我的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>

The write() method writes HTML expressions or JavaScript code to a document. write()方法将HTML表达式或JavaScript代码写入文档。

The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML. write()方法主要用于测试:如果在完全加载HTML文档后使用它,它将删除所有现有的HTML。

Answer from: source 答案来自: 来源

   <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>

Try above code it will work fine.If you use document.write() overwritten body so should be use document.body.innerHTML . 尝试上面的代码可以正常工作。如果使用document.write()覆盖主体,则应使用document.body.innerHTML。

The Document.write function overwrites the document content when called, as stated by the Mozilla Developer Network: 如Mozilla开发人员网络所述,Document.write函数在调用时会覆盖文档内容:

Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open which will clear the document. 注意:当document.write写入文档流时,在关闭的(加载的)文档上调用document.write会自动调用document.open,这将清除文档。

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

document.write() will override your whole body element. document.write()将覆盖您的整个body元素。 If you want to override only specific parts, you could define a target and use innerHTML to change the text. 如果只想覆盖特定的部分,则可以定义一个目标并使用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