[問題] $.each內的function傳入變數

看板Ajax作者 (渾沌與秩序)時間9年前 (2016/01/18 18:11), 編輯推噓1(109)
留言10則, 3人參與, 最新討論串1/1
大家好,很抱歉我標題下的很奇怪 因為我很難很清楚的一句話描述我的問題 我的問題如下程式碼 就是我使用外掛原件去製作成圖片 然而我有很多div需要製作後在一起合併成PDF 問題就是我該如何在onrendered: function內 傳入index的數值進去,去知道說我現在是做第幾個DIV 然後存到array內 var imgData = []; $.each($(DivId), function(index, value) { imgData.push(null); html2canvas($(this), { onrendered: function(canvas) { imgData[index] = CanvasResize(canvas); } }); }); // 210mm = 793.700787px // 50px = 13.229167mm setTimeout(function() { var pdf = new jsPDF('p', 'mm', [297, 210]); $.each($(DivId), function(index, value) { if(index!=0) pdf.addPage(); pdf.addImage(imgData[index], 'png', 20, 20, 170, 0, null, 'NONE'); } pdf.save(FileName + ".pdf"); document.body.style.zoom = 1.0; }, 3000); 網頁顯示 http://pastie.org/10693231#2-9 謝謝大家:) -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 59.124.29.189 ※ 文章網址: https://www.ptt.cc/bbs/Ajax/M.1453111873.A.578.html

01/18 20:24, , 1F
包一層 closure 起來
01/18 20:24, 1F

01/18 20:24, , 2F
onrendered: (function(index){return function(canvas){
01/18 20:24, 2F

01/18 20:25, , 3F
/*...*/}; })(index) }
01/18 20:25, 3F

01/18 20:25, , 4F
啊, 上一行最後的 } 是物件結束的 } @@
01/18 20:25, 4F

01/18 21:08, , 5F
第一次知道closure這東西!!!!!!!!!
01/18 21:08, 5F

01/18 21:08, , 6F
感謝L大!!!!!,明天來試試:)
01/18 21:08, 6F

01/20 23:46, , 7F
現在的話,比較推薦 Function.prototype.bind 歐...
01/20 23:46, 7F

01/20 23:47, , 8F
這個效果跟用closure差不多,但是版面乾淨很多
01/20 23:47, 8F

01/20 23:47, , 9F
缺點是太舊的瀏覽器可能不支援
01/20 23:47, 9F

01/20 23:50, , 10F
結果是(function(index, canvas){}).bind(null, index)
01/20 23:50, 10F
文章代碼(AID): #1MdBf1Lu (Ajax)
文章代碼(AID): #1MdBf1Lu (Ajax)