2011-10-16 102 views
1

我的代碼:爲什麼變量不會傳入jQuery.each?

$('.colorPick').click(function(e) { 
var x = e.pageX - this.offsetLeft; 
var y = e.pageY - this.offsetTop; 
var canvas2 = this.getContext('2d'); 
var data = canvas2.getImageData(x, y, 1, 1).data; 
var rgb = 'rgb(' + data[0] + ',' + data[1] + ',' + data[2] + ')'; 
$('.colorPicker').each(function(rgb) { 
    var x = this.width; 
    var y = this.height; 
    var canvas1 = this.getContext('2d'); 
    gradient1 = canvas1.createLinearGradient(0, 0, x, y); 
    gradient1.addColorStop(0, 'rgb(255, 255, 255)'); 
    gradient1.addColorStop(0.5, rgb); 
    gradient1.addColorStop(1, 'rgb(0, 0, 0)'); 
    canvas1.fillStyle = gradient1; 
    canvas1.fillRect(0, 0, x, y); 
}); 
}).disableSelection(); 

變量RGB不會傳遞到下一個。每個功能?

我是新來這個如果答案是簡單

回答

7

您定義rgb作爲參數傳遞給匿名函數,隱藏父範圍的rgb。如果你不聲明它作爲一個參數,它會發現從父範圍rgb(這是我想你想):

// ... 
var rgb = 'rgb(' + data[0] + ',' + data[1] + ',' + data[2] + ')'; 
$('.colorPicker').each(function() { 
    // ... 
+0

哦確定這麼簡單,哈哈這讓我卡住了半小時!謝謝 – nvcode