zl程序教程

您现在的位置是:首页 >  前端

当前栏目

《jQuery、jQuery UI及jQuery Mobile技巧与示例》——3.11 技巧:使用clone()复制元素

jQueryUI 技巧 示例 元素 复制 mobile clone
2023-09-11 14:17:44 时间

本节书摘来自异步社区《jQuery、jQuery UI及jQuery Mobile技巧与示例》一书中的第3章,第3.11节,作者:【荷】Adriaan de Jonge , 【美】Phil Dutson著,更多章节内容可以访问云栖社区“异步社区”公众号查看

3.11 技巧:使用clone()复制元素

如果说分离和重新添加元素只是能够移动它们,那么怎样用高效的方法来复制元素呢?为了满足这种需求,jQuery提供了clone()函数。代码清单3-11演示了如何使用clone()函数来模拟在表单中重复添加元素。重复元素集是一个隐藏div的副本。

代码清单3-11 使用clone()模拟在表单中添加重复元素

00 !DOCTYPE html 

02 html lang="en" 

03 head 

04 title The clone() function /title 

05 style 

06 /* 请将下列代码移至一个外部的

07 .css 文件 */

08 div#template {

09 display: none;

11 /style 

12 /head 

13 body 

15 h2 Add rows under the repeating fields header using the 

16 button below /h2 

18 form action="" method="post" 

20 h2 Single fields /h2 

22 label for="first" First /label 

23 input type="text" name="first" br 

25 label for="second" Second /label 

26 input type="text" name="second" br 

28 h2 Repeating fields /h2 

30 button id="add-row" Add row /button br 

32 div id="repeat" /div 

34 /form 

36 div id="template" 

37 label for="third" Third /label 

38 input type="text" name="third" /br 

40 label for="fourth" Fourth /label 

41 input type="checkbox" name="fourth" /br 

42 /div 

44 script src="http://code.jquery.com/jquery-1.7.2.min.js" /script 

46 script 

47 // 请将下列代码移至一个外部的.js文件中

48 $(document).ready(function() {

49 var rowCount = 0;

51 $(#add-row).click(function() {

52 $(#template *)

53 .clone()

54 .filter(input)

55 .attr(name, function(index, name) {

56 return name +[ + rowCount + ];

57 })

58 .end()

59 .appendTo(#repeat);

60 rowCount++;

62 // 如果点击处理函数是绑定在 button 元素上的并且这个按钮元素 

63 // 在 form 元素里面, return false语句会阻止页面重新加载,

64 // 以免无意间导致clone操作失败

65 return false;

66 });

68 });

69 /script 

70 /body 

71 /html 

第53行调用clone()之前的代码都非常简单。在第54~58行,代码筛选出input元素并更改了它们的name属性值,以确保每个值在表单中都是唯一的。当提交这个表单的时候,结果看起来像是一组重复的元素。clone()函数还可以接受两个额外的参数,使得克隆出来的元素能包含任何元素数据以及绑定事件的副本。两个参数都是布尔类型的,第一个参数指是否复制被克隆元素的数据和绑定事件,第二个参数指是否复制被克隆元素的所有后代元素的数据和绑定事件1。


异步社区 异步社区(www.epubit.com)是人民邮电出版社旗下IT专业图书旗舰社区,也是国内领先的IT专业图书社区,致力于优质学习内容的出版和分享,实现了纸书电子书的同步上架,于2015年8月上线运营。公众号【异步图书】,每日赠送异步新书。