2012-04-08 74 views
2

我試圖定義一個函數,可以更好地認爲:在jQuery中,如何使用選擇器作爲參數定義函數?

var photoWidth = $('#photo_preview').width(); 
var photoHeight = $('#photo_preview').height(); 

if (imgHeight > imgWidth){ 
    $('#photo_preview').css('width','100'); 
    } 

我的目標是創建一個會像一個函數:

resizePhoto(theselector); 

...與參數「theselector」是$('#photo_preview')或任何其他選擇器。

注:我不能使用這個類。

我該怎麼辦?

回答

5
function resizePhoto(selector){ 
    var photoWidth = $(selector).width(); 
    var photoHeight = $(selector).height(); 

    if (imgHeight > imgWidth){ 
    $(selector).css('width','100'); 
    } 
} 

...

resizePhoto('#photo_preview'); //Usage 
+0

簡直太神奇了。 – 2012-04-08 22:26:03

3
function(selector) { 
    var $jq = $(selector); 
    var imgWidth = $jq.width(); 
    var imgHeight = $jq.height(); 

    if (imgHeight > imgWidth){ 
     $jq.css('width','100px'); 
    } 
} 
相關問題