jQuery clone()方法绑定事件

先看如下代码:

 1 (function ($) {
 2 
 3     var div = $("<div></div>").css({width: "100px", height: "100px"});
 4     var colors = ["red", "blue", "yellow"];
 5     for (var c = 0; c < colors.length; c++) {
 6         var perDiv = div.clone();
 7         perDiv.css({
 8             background: colors[c]
 9         });
10         perDiv.click(function () {
11             console.log(colors[c]);
12         });
13         $("body").append(perDiv);
14     }
15 
16 })($);

效果图:

无论点击那个div都是输出 underfined

所以此代码不能解决每个div点击出现不同的事件。

改进代码:

 1 (function ($) {
 2 
 3     var div = $("<div></div>").css({width: "100px", height: "100px"});
 4     var colors = ["red", "blue", "yellow"];
 5     for (var c = 0; c < colors.length; c++) {
 6         var perDiv = div.clone();
 7         perDiv.css({
 8             background: colors[c]
 9         });
10         perDiv.addClass("a"+c);
11         $("body").append(perDiv);
12     }
13 
14     for (var e=0;e<colors.length;e++){
15         $(".a"+e).click(function () {
16             console.log($(this));
17         });
18     }
19 })($);

效果:

如图,每当点击一个对应就输出一个信息。

总结:给每个元素添加个class或id 就行了╮(╯▽╰)╭

 

补充:2016-09-24

先看代码:

 1 $(function () {
 2 
 3     var colors = ["red", "blue", "green"];
 4     var div = $("<div></div>").css({width: "100px", height: "100px"});
 5 
 6     for (var i = 0; i < colors.length; i++) {
 7         var odiv = div.clone();
 8         $("body").append(odiv);
 9         odiv.index = i;
10         odiv.css({background: colors[odiv.index]});
11     }
12 });

效果图:

看效果和上面一样。

这个的好处:没有添加类名,还实现了  "有分别"

思路:通过给odiv附加个属性index来保存与其他odiv的不同

感觉这样写 高大上 有木有。。

补充:2016-11-30 10:07:36

 1    var colors = ["red", "blue", "green"];
 2         var div = $("<div></div>").css({width: "100px", height: "100px"});
 3         function cloneDiv(num) {
 4             for (var i = 0; i < num; i++) {
 5                 var odiv = div.clone();
 6                 odiv.css("background", colors[i]);
 7                 $("body").append(odiv);
 8                 odiv.on("click", function () {
 9                     console.log(this);
10                 })
11             }
12         }
13         cloneDiv(colors.length);

运用this,实现不同。。

posted @ 2016-09-07 18:46  晨落梦公子  阅读(5136)  评论(0编辑  收藏  举报