我有一个下拉菜单,它根据所选的选择构建一个表单。因此,如果有人选择“foobar”,它会显示一个文本字段,如果他们选择“cheese”,它会显示单选按钮。然后,用户可以在这些表单中输入数据。唯一的问题是,当他们添加新的表单元素时,所有其余信息都会被删除。我目前使用以下内容添加到表单:
document.getElementById('theform_div').innerHTML =
document.getElementById('theform_div').innerHTML + 'this is the new stuff';
如何让它保留表单中输入的内容并将新字段添加到末尾?
I have a drop down which builds a form based of the selections that are selected. So, if someone selects 'foobar', it displays a text field, if they choose 'cheese', it displays radio buttons. The user can then enter data into these forms as they go along. The only problem is that when they add a new form element, all the rest of the information is erased. Im currently using the following to do add to the form:
document.getElementById('theform_div').innerHTML =
document.getElementById('theform_div').innerHTML + 'this is the new stuff';
How can I get it to keep whatever has be enetered in the form and also add the new field to the end?
发布评论
评论(6)
设置
innerHTML
会破坏元素的内容并从 HTML 重建它。您需要构建一个单独的 DOM 树并通过调用
appendChild
添加它。例如:
使用 jQuery 可以更容易地做到这一点。
Setting
innerHTML
destroys the contents of the element and rebuilds it from the HTML.You need to build a separate DOM tree and add it by calling
appendChild
.For example:
This is much easier to do using jQuery.
第一步:
将 jQuery 添加到标头:
第二步:
将数据附加(而不是替换)到 DIV,如下所示:
Step One:
Add jQuery to your headers:
Step Two:
Append, don't replace, data to your DIV like this:
不要使用
innerHTML
创建表单元素。使用innerHTML
,您将使用新的 HTML 覆盖旧的 HTML,这将重新创建所有元素。相反,您需要使用 DOM 来创建和附加元素。示例
Don't use
innerHTML
to create the form elements. WithinnerHTML
you're overwriting the old HTML with new HTML which will recreate all the elements. Instead you need to use the DOM to create and append the elements.EXAMPLE
不使用框架(如 jQuery、Dojo、YUI)的最正确方法是:
innerHTML
,虽然大多数浏览器都支持,但不符合标准,因此不能保证正常工作。The most correct way to do it without using a framework (like jQuery, Dojo, YUI) is:
innerHTML
, although supported by most browsers, is not standard compliant and - therefore, not guaranteed to work.我建议使用 jQuery 及其
追加
函数。I would suggest using jQuery and its
append
function.如果您想使用 HTML 字符串生成元素,如
innerHTML
那样,一个不错的选择是insertAdjacentHTML
函数,及其position
参数:如您所见 Mozilla 的文档,除了更快之外,这还解决了您遇到的问题因为该函数不会重新解析父元素:
但是,如果您只想添加纯文本,而不是 HTML 代码,那么有一个类似的函数 专为名为
插入AdjacentText
:If you want to generate the element using an HTML string, as
innerHTML
does, a great option is theinsertAdjacentHTML
function, with it'sposition
parameter:As you can see from Mozilla's documentation, besides being faster, this solves the problem you had because the function doesn't reparse the parent element:
However, if you just want to add plain text, not HTML code, then there is a similar function made just for that called
insertAdjacentText
: