通常,绑定到原始元素的任何事件处理程序都不会
复制到克隆。可选的 withDataAndEvents 参数允许
我们改变这种行为,并改为复制所有
事件处理程序也绑定到元素的新副本。作为
jQuery 1.4,所有元素数据(由 .data() 方法附加)也是
复制到新副本。
但是,元素数据中的对象和数组不会被复制和
将继续在克隆元素和原始元素之间共享
元素。要深度复制所有数据,请手动复制每个数据:
var $elem = $('#elem').data( "arr": [ 1 ] ), // Original element with attached data
$clone = $elem.clone( true )
.data( "arr", $.extend( [], $elem.data("arr") ) ); // Deep copy to prevent data sharing
从 jQuery 1.5 开始,withDataAndEvents 可以选择增强
deepWithDataAndEvents 复制所有子节点的事件和数据
克隆的元素。
来源:http://api.jquery.com/clone/
我相信您正在寻找上面的代码,它实际上复制了与元素关联的数据,而不是在元素之间共享数据。
更新
在搞砸了几分钟后,这就是我想出的:
//create original datepicker
var $input = $("input").datepicker(),
//clone the datepicker, copy the data from the original, and change the ID of the new element
$clone = $input.clone(true).data( "datepicker", $.extend( true, {}, $input.data("datepicker") ) ).attr('id', 'test-id');
//now change the references in the data for the clone to point to the clone
$clone.data('datepicker').input = $clone;
$clone.data('datepicker').id = 'test-id';
//add the clone to the DOM
$("body").append("<br><br><br>Input 2: ").append(
$clone
);
还有一个演示:http://jsfiddle.net/YUkZw/5/