本文實例講述了jQuery使用each方法與for語句遍歷數組。分享給大家供大家參考,具體如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="jquery-1.6.2.js" type="text/javascript"></script> <script type="text/javascript"> var array=["huangbiao","24","boy"]; var length = array.length; function forFunc(){ var result = ""; for(var i = 0; i < length; i++){ result=result.concat(array[i]+" ; "); } $("#forFunc").html(result); return true; } function eachFunc(){ var result = ""; $(array).each(function(i,n){ //下面兩種方式實現的效果是一樣的 //result=result.concat(array[i]+" ; "); result=result.concat(n+" ; "); }); $("#eachFunc").html(result); } </script> <title>無標題文檔</title> </head> <body> <button onclick="forFunc()">forFunc</button><br> <div id="forFunc"></div> <button onclick="eachFunc()">eachFunc</button><br> <div id="eachFunc"></div> </body> </html>