gpt4 book ai didi

jquery - 如何克隆已被 jQuery UI Widget 绑定(bind)的元素?

转载 作者:行者123 更新时间:2023-12-03 23:04:45 26 4
gpt4 key购买 nike

以下代码无法正确克隆输入元素。单击/关注克隆的输入将在原始输入上打开日期选择器。

http://jsfiddle.net/musicisair/YUkZw/

<input>
<script>
var input = $("input").datepicker();
$("body").append("<br>Input 2: ").append(
input.clone(true);
);
</script>

是否有正确的方法来克隆已与 jQuery UI 小部件绑定(bind)的元素?如果是这样,那是什么?

最佳答案

Normally, any event handlers bound to the original element are not copied to the clone. The optional withDataAndEvents parameter allows us to change this behavior, and to instead make copies of all of the event handlers as well, bound to the new copy of the element. As of jQuery 1.4, all element data (attached by the .data() method) is also copied to the new copy.

However, objects and arrays within element data are not copied and will continue to be shared between the cloned element and the original element. To deep copy all data, copy each one manually:

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

As of jQuery 1.5, withDataAndEvents can be optionally enhanced with deepWithDataAndEvents to copy the events and data for all children of the cloned element.

来源: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/

关于jquery - 如何克隆已被 jQuery UI Widget 绑定(bind)的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9725488/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com