为什么函数不会匹配不同数组的宽度和高度
Why won't function match width and height from varying arrays?
我之前有以下函数,它被冗余的重复变量所破坏。所以我想改进它并将图像存储到数组中。但是,即使使用与先前脚本相同的上下文标记,它也不会从数组中检测到图像值并将其与item
匹配。我不知道为什么。我将每个项目设置为检查不同图像大小的实例,然后执行if
状态的操作。
小提琴(非工作脚本):
工作小提琴:(工作脚本):
我不是没有表达数组的正确值吗?我觉得我想太多了,忽略了一些小事。但老实说,我被难住了。
var top_horizontalvert_mobile = ['320 x 50', '300 x 100', '300 x 50', '250 x 250', '120 x 60', '240 x 400', '180 x 150', '125 x 125'];
var top_horizontal_desktop = ['729 x 90', '468 x 60'];
var bottom_horizontal_desktop = ['930 x 180', '336 x 280'];
var bottom_vert_mobile = ['234 x 60'];
var middle_vert_mobile = ['300 x 250'];
var right_vert_desktop = ['120 x 600', '160 x 600'];
$("#carousel-container-mobile, #carousel-container-desktop").on('slid.bs.carousel', function() {
$('.item').each(function() {
var imgs = $('.item');
var w = $(img).width();
var h = $(img).height();
var img = $('img', this);
if (w == top_horizontalvert_mobile && h == top_horizontalvert_mobile) {
img.addClass('top, smaller-img');
}
if (w == top_horizontal_desktop && h == top_horizontal_desktop) {
img.addClass('top, larger-img');
}
if (w == bottom_vert_mobile && h == bottom_vert_mobile) {2
img.addClass('bottom, smaller-img');
}
if (w == bottom_horizontal_desktop && h == bottom_horizontal_desktop) {
img.addClass('bottom, larger-img');
}
if (w == middle_vert_mobile && h == middle_vert_mobile) {
img.addClass('middle, smaller-img');
}
if (w == right_vert_desktop && h == right_vert_desktop) {
img.addClass('right, smaller-img');
}
if (w == middle_vert_mobile && h == middle_vert_mobile) {
img.addClass('right, smaller-img');
}
});
});
两个脚本之间的主要区别在于如何比较值。
在工作脚本中,您直接比较数字:
if (img.width() == 320 && img.height() == 50)
在非工作脚本中,您实际上是将数字与数组进行比较。
if (w == top_horizontalvert_mobile)
如果我们换成更文字的值:
if (img.width() == ['320 x 50', '300 x 100', '300 x 50', '250 x 250', '120 x 60', '240 x 400', '180 x 150', '125 x 125']
而且永远不会有数字将成为数组的情况,因为数组是不同的数据类型。
根据我所看到的,您正在尝试将每个宽度和高度与数组中的每个值进行比较,但这需要以下最少的步骤:
-
将数组转换为多维数字数组,因为将其保留为字符串需要您解析数据(这比必要的工作量更多。因此,您将拥有[[320,50],[300,100]...],而不是
[320 x 50', '300 x 100' ...]
` -
使用 for 循环循环访问数组的每个值,以便进行比较。请参阅Codecademy的循环教程以了解更多信息。
如果您有任何其他问题,请告诉我!
顺便说一句,在查看您的工作脚本并寻找您要执行的操作之后,您似乎正在尝试通过jQuery根据图像大小应用不同的样式。您为什么不将类直接应用于图像本身,因为您似乎对图像大小有非常具体的要求?
- 如何在映射数组中添加换行符
- javascript结合了数组和字典
- 需要帮助设置json数组
- 不能从angular2中的子组件指定父组件中的数组
- 使用JS将数组转换为json对象
- 数组在递归方法中设置为null
- knockoutjs可观察数组
- Javascript-如何读取json文件中的列并将其保存在Javascript数组中
- 将数组从PHP传递到Javascript
- JavaScript数组排序(函数)用于对表行进行排序,而不是排序
- 在函数中添加数组元素的数值
- 无法通过数组映射绑定
- javascript中的数组出错
- 如何使用 node.js 比较两个 json 数组
- Javascript(Angular)从一个对象数组到第二个数组查找值
- 为什么函数不会匹配不同数组的宽度和高度
- 用Javascript创建一个给定宽度和高度的二维数组
- 如何使用CSS在JavaScript中设置数组中“td”的高度
- JavaScript从给定宽度和高度的平面数组中确定行、列和元素的相对位置
- 使用Math.max获取数组中元素的最大宽度/高度