使用 jQuery 克隆
我有一个允许用户推荐朋友的表格。我想在“朋友电子邮件”和“朋友姓名”这两个输入字段下方添加一个链接,该链接将克隆“朋友框”一次并将其添加到下面。另外,“好友电子邮件”和“好友姓名”的 name 属性建议为 name="friend_email[0]"
和 name="friend_name[0]"
此处。克隆和增加下标的最佳方法是什么?代码如下:
<div class="friend-box">
<div class="field">
<span><label for='friend_name'><strong>Friend's Name *</strong></label> </span>
<input id='friend_name' name='friend_name[0]' type='text' />
</div>
<div class="field">
<span><label for='friend_email'><strong>Friend's Email *</strong></label></span>
<input id='friend_email' name='friend_email[0]' type='text' />
</div>
</div>
执行此操作的最佳方法是什么?例如,我遇到的问题之一是,当我克隆“friend-box”一次然后两次时,它显然以指数方式克隆它。所以我猜我还需要在那里有一个 ID 号并递增它。或者,这是我看到的另一种方法,是在页面加载时克隆“朋友框”并继续从内存中克隆它。
谢谢, 瑞安
I have a form that allows users to refer friends. I want to add a link below the two input fields, "friend email" and "friend name", that will clone "friend-box" one time and add it below. In addition, the name attribute of "friend email" and "friend name" are name="friend_email[0]"
and name="friend_name[0]"
as suggested here. What's the best way to clone and increment the subscript? Here's the code:
<div class="friend-box">
<div class="field">
<span><label for='friend_name'><strong>Friend's Name *</strong></label> </span>
<input id='friend_name' name='friend_name[0]' type='text' />
</div>
<div class="field">
<span><label for='friend_email'><strong>Friend's Email *</strong></label></span>
<input id='friend_email' name='friend_email[0]' type='text' />
</div>
</div>
What's the best way to do this? One of the problems I had for example, is that when I cloned "friend-box" once and then twice, it obviously cloned it exponentially. So I'm guessing I need to have an ID number in there as well and increment it. Or, which is another method I saw, is to clone the "friend-box" when the page loads and keep cloning it from memory.
Thanks,
Ryan
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我在这里创建了一个示例:
http://jsfiddle.net/K8hhW/5/
您无需担心增加数字在括号中,表格会自动为您执行此操作。
I have created an example here:
http://jsfiddle.net/K8hhW/5/
You do not need to worry about incrementing the numbers in the brackets, the form does this automatically for you.
不需要指定索引[0],只要输入[]浏览器就会自动递增索引。
至于你的问题,我会这样做: http://jsfiddle.net/EJv4g/3/
基本上,我添加了一个
div.friend-boxes
来包装所有的朋友框。我使用 jQuery 获取第一个朋友框,克隆它,然后重置输入字段值(以防它们被填充)。然后,我将其附加到.friend-boxes
元素中。如果您希望将其添加到前面,可以将
append
更改为prepend
。希望这有帮助!
You don't need to specify the index [0], as long as you put [] the browser will automatically increment the index.
As for your question, here's how I would do it: http://jsfiddle.net/EJv4g/3/
Basically, I added a
div.friend-boxes
which wraps all friend boxes. I use jQuery to obtain the first friend box, clone it then reset the input field values (in case they were filled). I then append it to the.friend-boxes
element.You can change the
append
toprepend
if you want it to be prepended.Hope this helps!