先看如下代码:
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,实现不同。。
原文链接: https://www.cnblogs.com/chenluomenggongzi/p/5850538.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/240121
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!