javascript - 如何将 jquery 选择传递到函数中?

标签 javascript jquery function

我尝试搜索,但找不到我要找的东西。希望这对某人来说非常简单。

这是我开始的代码,我想将其转换为函数。显然有一种方法可以做到这一点,所以我不必重复。

var fullWidth = $('.full-img').width();
var paddBottom = fullWidth * .75;
$('.full-img').css('padding-bottom', paddBottom);

var thumbWidth = $('.img-box').width();
var thumbBottom = thumbWidth * .75;
$('.img-box').css('padding-bottom', thumbBottom);

这是我尝试过的

function aspectRatioFix(main, thumb) {
    var fullWidth = main.width();
    var paddBottom = fullWidth * .75;
    main.css('padding-bottom', paddBottom);

    var thumbWidth = thumb.width();
    var thumbBottom = thumbWidth * .75;
    thumb.css('padding-bottom', thumbBottom);
}

    aspectRatioFix('.full-img', '.img-box');

我收到错误“Uncaught TypeError: main.width is not a function”

有没有办法可以循环遍历我的函数来处理脚本的两个部分,而不是仅仅复制我所拥有的内容? 谢谢!

最佳答案

函数 aspectRatioFix 需要 jQuery 对象,因此您必须传入 jQuery 对象而不是像这样的选择器(字符串):

aspectRatioFix($('.full-img'), $('.img-box'));

如果您有许多图像及其缩略图,并且想要为所有图像应用代码,请使用 .each,如下所示:

var $mains = $('.full-img'),
    $thumbs = $('.img-box');

$mains.each(function(index) {
    // this:  is the main image
    // index: is its index so we can access the according thumb from $thumbs

    aspectRatioFix($(this), $($thumbs[index])); // apply the aspectRatioFix on this main image, and on it's thumb from the $thumbs object (both this and $thumbs[index] are node elements so we have to wrap them in a jQuery object using $())
});

关于javascript - 如何将 jquery 选择传递到函数中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43283973/

相关文章:

r - 如何使用lapply定义多个变量?

C++ 应该重载函数还是 if 语句就足够了?

javascript - 如何在 AJAX 请求期间禁用 anchor 标记并更改 html()

php - 500 内部服务器错误使用 jquery

javascript - $ ("<p>") 和 $ ("p") 有什么区别

javascript - 输入文本框 HTML Bootswatch 有错误

C++:将结构传递给函数,无法理解语法

javascript - 通过网络链接在 Whatsapp 中分享信息

javascript - for循环内的AngularJS $timeout

javascript - 使用 jQuery/Javascript 通过 id 下载文件