日期:2014-05-16 浏览次数:20480 次
var images = ["1", "2", "3", "4"]; $(function(){ $.each(images, function (i) { var divNew = $('<div style="width:20px;height:10px; background-color:blue;float:left;margin:2px"></div>'); $(divNew).click(function () { alert(images[i]); }); }); });
<!DOCTYPE HTML> <html> <head> <meta charset="gb2312" /> <title></title> </head> <body> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <script> function $(el){ return typeof el == 'string' ? document.getElementById(el) : el; } function $t(name, cot){ cot = cot || document; return cot.getElementsByTagName(name); } function makeArray( obj ){ var arr = []; for ( var i = 0, len = obj.length; i < len; i++ ){ arr.push(obj[i]); } return arr; } Array.prototype.each = function(fn){ for ( var i =0, len = this.length; i < len; i++ ){ fn.call( null, i, this[i] ); } } var objs = $t('div'); var arr = makeArray(objs); arr.each(function(i, k){ k.onclick = function(){ alert(i) } }) </script> </body> </html>