Dav*_*och 5 jquery clone jquery-ui datepicker
以下代码无法正确克隆输入元素。单击/聚焦在克隆的输入上会在原始输入上打开日期选择器。
http://jsfiddle.net/musicisair/YUkZw/
<input>
<script>
var input = $("input").datepicker();
$("body").append("<br>Input 2: ").append(
input.clone(true);
);
</script>
Run Code Online (Sandbox Code Playgroud)
有没有正确的方法来克隆已与jQuery UI小部件绑定的元素?如果是这样,那是什么?
通常,绑定到原始元素的任何事件处理程序都不会复制到克隆中。可选的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
Run Code Online (Sandbox Code Playgroud)
从jQuery 1.5开始,可以使用deepWithDataAndEvents增强withDataAndEvents的功能,以复制克隆元素的所有子级的事件和数据。
资料来源: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
);
?
Run Code Online (Sandbox Code Playgroud)
和演示:http : //jsfiddle.net/YUkZw/5/
| 归档时间: |
|
| 查看次数: |
1960 次 |
| 最近记录: |