javascript - 如果我添加 div,insertBefore 将停止在表单中工作

标签 javascript html css

我创建了动态表单,可以在其中添加任意数量的作者。

<form action="uploadtodb.php" target="dummyframe" method="post" name="myform">
            <p>
            Authors last name:      <input type="text" name="authorln[]" size="32" />
            Authors first names:    <input type="text" name="authorfns[]" size="32" />
            </p>
            <p id="add_author_button">
            <button type="button" onclick="add_author()">Add new author</button>
            <button type="button" onclick="remove_author()">Remove last author</button>
            </p>
</form>

其中函数 add_author() 添加到 myform 新段落,如下所示 para

document.myform.insertBefore(para, document.getElementById("add_author_button"));

它工作得很好,但后来我想给它添加一些样式。所以我添加了div:

<form action="uploadtodb.php" target="dummyframe" method="post" name="myform">
        <div id="authors">
            <p>
            Authors last name:      <input type="text" name="authorln[]" size="32" />
            Authors first names:    <input type="text" name="authorfns[]" size="32" />
            </p>
            <p id="add_author_button">
            <button type="button" onclick="add_author()">Add new author</button>
            <button type="button" onclick="remove_author()">Remove last author</button>
            </p>
        </div>
</form>

修改后按钮没有反应。

最佳答案

尽管您可以使用document.<form name>对于表单,您不能对像作者 div 这样的任意元素执行此操作。为什么不直接使用 getElementById()

document.getElementById("authors").insertBefore(para, document.getElementById("add_author_button"));

关于javascript - 如果我添加 div,insertBefore 将停止在表单中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36562929/

相关文章:

html - 分享按钮上的CSS

css - 如何命名基 css 类以便其他用户可以轻松关联

javascript - 如何将 form_for 与非输入元素一起使用?

javascript - 如何将 jquery 动画应用于我的弹出窗口?

javascript - 正则表达式中美元符号的含义

php - Jquery Ajax 调用能否从 PHP 成功接受对象?

javascript - 创建点击进入实际 map 的 map 示例

html - Bootstrap - 如何将列高设置为多行?

java - OWASP HTML Sanitizer 清理评论

css - div 中的垂直对齐被忽略