Javascript添加动态输入字段 [英] Javascript Add Dynamic Input Field
问题描述
我对Javascript一点都不好,所以我来这里寻求帮助。
我所拥有的是一个表单,其中包含一个添加的链接附加网址字段。我想要它,所以当用户点击它时,它将填充默认url字段下的附加字段,具有唯一的输入名称,例如url_input1,如果他们再次单击它以添加另一个url输入,那么输入的名称将是url_input2等。
如何使用Javascript执行此操作?
对于像jQuery这样的JS库来说,这是一个完美的工作。有关此jQuery示例实现,请参阅此。
如果你想使用纯JavaScript和DOM操作手工制作,你有两个选择:
- 你可以做createElement和combine使用appendChild(请参阅此或这个)或者insertBefore(参见 this 或这个)取决于插入点的位置。 (按照Sonic Soul的建议)
- 使用innerHTML并通过将控件的HTML传递给它来添加控件,这与我的spike中的jQuery方法非常相似。 (如Joshua所述)
选项1比选项2慢。
<个人而言,我将使用jQuery,因为它会抽象一些可能导致一些跨浏览器问题的DOM实现,并且仅仅因为它更好,更强大,可以做这样的事情。
I'm not good with Javascript at all, so I come here to seek assistance.
What I have is a form, with a link that says "Add additional URL field". I want it so when a user clicks that, it will populate an additional field underneath the default url field, with a unique input name, such as url_input1, and if they click it again to add another url input, the name of that input would be url_input2, etc.
How can I do this with Javascript?
This is a perfect job for JS library like jQuery. For a jQuery example implementation of this, see this.
if you want to handcraft this using pure JavaScript and DOM manipulation, you have 2 choices:
- You can do createElement and combine that with either appendChild (see this or this) or insertBefore (see this or this) depending where your insert point is. (as suggested by Sonic Soul)
- Use innerHTML and add the control by passing the HTML of control into it, which is quite similar to the jQuery approach that is in my spike. (as described by Joshua)
Option 1 is slower than Option 2.
Personally, I'll use jQuery since it will abstract some of DOM implementation that might cause some cross browser issues and simply because it's nicer and very powerful for doing stuffs like this.
这篇关于Javascript添加动态输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!