【问题标题】:javascript why i cannot appendchild to html div using javascript functionjavascript 为什么我不能使用 javascript 函数将子元素附加到 html div
【发布时间】:2020-11-16 17:19:22
【问题描述】:

我需要使用javascript将子控件附加到html元素,问题是子控件在调用函数时出现并直接消失,子控件必须在表单标签中

这是我将子元素附加到 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>

元素h1 被添加到布局中会立即出现并消失,但是当我删除&lt;form&gt; 时它可以完美运行

【问题讨论】:

  • 不知道,先将其减少为minimal reproducible example?除了options.text 应该是options.textContentfor ... in ... 用于数组,你应该从不 使用这些代码大部分看起来都很好(尽管到处都违反了JS 命名约定),并且应该是for ... of ... ,或arr.forEach(...)
  • 选择元素已正确填充并显示,但毫秒后消失,似乎页面正在刷新
  • 可能您将您的选择添加到由 React 或 Vue 等 JS 框架之一生成和控制的 dom 元素 (tab_logic) 中?
  • 不,我没有在我的代码中使用它,这是我要添加元素的 div &lt;div class="form-group" id="tab_logic"&gt;
  • 再次:我们不知道,因为您没有告诉我们一切。请花点时间组建minimal reproducible example。通常,在减少您自己发现问题的同时,您甚至不需要我们,但如果问题仍然存在完全减少后,现在我们可以提供帮助,因为您所说的我们是唯一重要的细节。现在,这是非常不正确的。

标签: javascript html appendchild


【解决方案1】:

当您按下按钮时,看起来表单元素正在提交,刷新页面并使标题消失。 您可能应该问自己:我真的需要表格吗?是否有一些输入应该由服务器处理?

如果你真的需要,可以试试prevent the form from submitting

此外,正如this SO Question 中所指出的,您可以通过将其type 指定为“按钮”来阻止按钮提交表单。

【讨论】:

    【解决方案2】:

    同意@Drago96表单提交和页面刷新。

    form 的意义何在。如果你只是附加一个元素

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-22
      • 2021-06-29
      • 2015-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多