简体   繁体   English

javascript 为什么我不能使用 javascript function appendchild 到 html div

[英]javascript why i cannot appendchild to html div using javascript function

i need to append a child control to html element using javascript, the problem is that the child is appear when call the function and disappear directely the child must be in a form tag我需要 append 使用 javascript 对 html 元素进行子控件,问题是当调用 function 时出现子控件并直接消失 子控件必须在表单标签中

this is the code when i append child to the html elemet这是当我 append 孩子到 html 元素时的代码

<html>
 <body>
  <form  >
<button onclick="create()">Create Heading</button>

</form>

    <script>
  function create() {
    var h1 = document.createElement('h1');
    h1.textContent = "New Heading!!!";
    h1.setAttribute('class', 'note');
    document.body.appendChild(h1);
  }
</script>
   </body>
   </html>

the element h1 is added to the layout appear and disappear immediately but when i remove the <form> it works perfectly元素h1被添加到布局中,立即出现并消失,但是当我删除<form>时,它工作得很好

It looks like the form element is submitting when you press the button, refreshing the page and making the header disappear.当您按下按钮时,看起来表单元素正在提交,刷新页面并使 header 消失。 You should probably ask yourself: should I really need a form?您可能应该问问自己:我真的需要表格吗? Are there some inputs that should be handled by the server?服务器是否应该处理一些输入?

If you really need it, then you can try to prevent the form from submitting如果你真的需要它,那么你可以尝试阻止表单提交

Also, as pointed out in this SO Question you can prevent the button to submit the form by specifying its type as 'button'.此外,正如此 SO 问题中所指出的,您可以通过将其type指定为“按钮”来阻止按钮提交表单。

Agreeing with @Drago96 Form submits and page refreshes.同意@Drago96表单提交和页面刷新。

What is the point of the form . form有什么意义。 if you are only appending an element如果你只是追加一个元素

<body>
    <button onclick="create()">Create Heading</button>
    <script>
        function create() {
            var h1 = document.createElement('h1');
            h1.textContent = "New Heading!!!";
            h1.setAttribute('class', 'note');
            document.body.appendChild(h1);
        }
    </script>
</body>

</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM