jQuery clone() 覆盖以前克隆的元素
我有一个表单模板,需要动态复制它以与弹出窗口的新实例关联。我正在使用 jQuery 的 clone() 方法来执行此操作。每当我尝试创建模板的新实例时,先前创建的表单选项都会被删除。
示例代码: HTML:
<div id="template" class="modifyDiv">
<div class="options">
<label><input type="radio" class="foo" checked="checked" value="bar" name="displayMode">Foo</label>
<label><input type="radio" class="blah" value="biz" name="displayMode">Blah</label>
</div>
</div>
JavaScript
popup.create = function() {
// create popup stuff
createViewSettings(popup);
}
createTemplate = function(popup) {
...
var modifyDiv = $("#template").clone(true).removeAttr("id");
modifyDiv.appendTo($(document.body));
modifyDiv.data("popup",popup);
popup.data("settings",modifyDiv);
... }
发生的事情是这样的:当我创建一个新的弹出窗口时,设置是完美的。但是当我创建第二个时,原始的“displayMode”复选框的值变得未定义。
我已经逐步完成,似乎导致问题的行是:
var clone = elem.cloneNode(true)
在 jquery 中的克隆定义中。我正在使用 v1.5.1
编辑:此问题出现在 Chrome 14.0.835.202 中,但不在 IE8 中 编辑:当输入是单选按钮而不是复选框时,会出现此问题。
I have a form template that I need to copy dynamically to associate with new instances of a popup. I'm using jQuery's clone() method to do so. Whenever I try to create a new instance of the template, the previously created forms' options are erased.
Sample code:
HTML:
<div id="template" class="modifyDiv">
<div class="options">
<label><input type="radio" class="foo" checked="checked" value="bar" name="displayMode">Foo</label>
<label><input type="radio" class="blah" value="biz" name="displayMode">Blah</label>
</div>
</div>
JavaScript
popup.create = function() {
// create popup stuff
createViewSettings(popup);
}
createTemplate = function(popup) {
...
var modifyDiv = $("#template").clone(true).removeAttr("id");
modifyDiv.appendTo($(document.body));
modifyDiv.data("popup",popup);
popup.data("settings",modifyDiv);
... }
What's happening is this: when I create a new popup the settings are perfect. But when I create a second one, the original "displayMode" checkbox's value becomes undefined.
I've stepped through and the line that seems to cause the issue is:
var clone = elem.cloneNode(true)
in the clone definition in jquery. I'm using v1.5.1
EDIT: This problem occurs in Chrome 14.0.835.202, but not in IE8
EDIT: This problem occurs when the inputs are radio buttons, not checkboxes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个愚蠢的问题;当您克隆带有单选按钮的 div 时,您必须确保新 div 的单选按钮具有唯一的名称,因为在给定页面上只能选择一个具有给定名称的单选按钮。
This is a dumb question; when you clone a div with radio buttons you have to make sure the new div's radio buttons have a unique name, because only one radio button with a given name can be selected on a given page.
您的答案部分正确。每个
现场演示:http://fiddle.jshell.net/DfBHh/19/
Your answer was partially correct. You can only have one radio group with a given name per
<form>
, but you can have as many forms as you want on a page. Replacing one of your wrapping<div>
elements with a<form>
should fix the issue:Live demo: http://fiddle.jshell.net/DfBHh/19/