单击按钮添加新的fieldset元素 [英] Add new fieldset elements with button click

查看:84
本文介绍了单击按钮添加新的fieldset元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用JavaScript可以通过单击按钮生成字段集中的所有元素吗?下面的代码显示了一个字段集中的两个文本框和一个textarea。当我按下添加项目按钮时,我想在该字段集中生成相同的文本框和textarea。

Is there any way with JavaScript to generate all the elements in the fieldset with the click of a button? Code below shows two textboxes and one textarea in a fieldset.When I press 'Add item button',I would like to generate the same textboxes and textarea within that fieldset.

非常感谢您的帮助。

<fieldset id="fieldset">
<legend id="legend">Professional development</legend>
<p>Item                     <input type ="text" size="25"   name="prof_item" /><br /></p>
<p>Duration                 <input type ="text" size="25"   name="prof_duration" /><br /></p>
<p>Enlargement              <label for="enlargement"></label><p></p>
                            <textarea name="textarea" cols="71" rows="5" id="prof_enlargement">
</textarea></p>
<p><input type="submit" name="Submit" value="Add new item" id="add_prof" /></p>
</fieldset>


推荐答案

您可以克隆它们。首先用父 div 包装那些元素,例如调用它模板:

You can clone them. First wrap those elements with parent div call it for example "template":

<div id="template">
  <p>Item <input type ="text" size="25" name="prof_item" /><br /></p>
  <p>Duration <input type ="text" size="25" name="prof_duration" /><br /></p>
  <p>Enlargement <label for="enlargement"></label></p>
   <p><textarea name="prof_enlargement" cols="71" rows="5" id=""></textarea></p>
</div>

第二个占位符将包含您添加的所有克隆:

Second have placeholder that will contain all the clones you add:

<div id="placeholder">
  <div id="template">
     <p>Item <input type ="text" size="25" name="prof_item" /><br /></p>
     ...
   </div>
</div>

最后这个JS代码会添加元素:

And finally this JS code will add the elements in there:

var _counter = 0;
function Add() {
    _counter++;
    var oClone = document.getElementById("template").cloneNode(true);
    oClone.id += (_counter + "");
    document.getElementById("placeholder").appendChild(oClone);
}

只需在按钮点击事件中调用添加功能..计数器需要避免为多个元素使用相同的ID。

Just call the function "Add" in the button click event.. the counter is required to avoid having same ID for more than one element.

实时测试用例: http://jsfiddle.net/yahavbr/eW6j4/

这篇关于单击按钮添加新的fieldset元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆