在jQuery中,如何使用选择器作为参数定义函数?

ale*_*186 3 javascript jquery

我正在尝试定义一个函数:

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

if (imgHeight > imgWidth){
    $('#photo_preview').css('width','100');
    }
Run Code Online (Sandbox Code Playgroud)

我的目标是创建一个类似于以下的函数:

resizePhoto(theselector);
Run Code Online (Sandbox Code Playgroud)

...参数"theselector"是$('#photo_preview')或任何其他选择器.

注意:我不能使用这个类.

我该怎么办?

Qui*_*son 6

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

  if (imgHeight > imgWidth){
    $(selector).css('width','100');
  }
}
Run Code Online (Sandbox Code Playgroud)

...

resizePhoto('#photo_preview'); //Usage
Run Code Online (Sandbox Code Playgroud)