Javascript 我如何正确地使用jQuery来修复这个fencepost案例?
我有一个函数Javascript 我如何正确地使用jQuery来修复这个fencepost案例?,javascript,jquery,algorithm,optimization,responsive-design,Javascript,Jquery,Algorithm,Optimization,Responsive Design,我有一个函数 function giveTheseEqualHeight ( selector ) { // selector: CSS selector of elements on the page to be forced to have the same height var these = $(selector); if (these.length < 2) return; these.height('auto'); var
function giveTheseEqualHeight ( selector )
{
// selector: CSS selector of elements on the page to be forced to have the same height
var these = $(selector);
if (these.length < 2) return;
these.height('auto');
var maxHeight = these.first().height();
these.each(function(){
var thisHeight = $(this).height();
if (thisHeight > maxHeight) maxHeight = thisHeight;
});
these.height(maxHeight);
}
通过加高小于最大高度元素的元素,将使所有h3
元素(属于服务列
类元素的后代)具有相同的高度
问题是这个循环
these.each(function(){
var thisHeight = $(this).height();
if (thisHeight > maxHeight) maxHeight = thisHeight;
});
不需要在第一次迭代时执行它的主体——这相当于无用的操作。我想从第二项开始,而不是这些。每个。这可能吗?jQuery有
切片。从第二个元素(索引1)切片。如果省略了结束,则它将一直切片到结束
these.slice(1).each(...);
使用大于
选择器选择索引大于所提供数字的所有元素
如果获得高度数组,然后使用本机数学获取最大值,则可以避免计算第一个元素的高度。最大值:
function giveTheseEqualHeight(selector) {
var these = $(selector);
if (these.length < 2) return;
these.height('auto');
var maxHeight = Math.max.apply(null, these.map(function(el) {
return $(this).height();
}));
these.height(maxHeight);
}
洛勒姆
试验
休息
在
west上测试
和rest
是否使用了切片
返回对象集的引用,还是复制了它们?@WebDevonPIPatAmazon.com内容与引用相同。只是包装jQuery对象不同。如果将maxHeight初始化为零,则不会重复工作:)@dtanders很好!我不会把时间浪费在这个微优化上。@Barmar PIP'n不容易:(@dtanders不会取笑我的用户名。这不是闹着玩的事。你确定这会更快吗?获取高度数组需要迭代元素。因此,这是通过长度N
的对象进行的额外迭代。如果你真的关心性能,那么首先不要使用jQuery,使用native loop并像现在一样进行比较。@WebDevonPIPatAmazon.com如果你真的关心速度,它有一个据说比Math.max.apply()快3倍的解决方案。
function giveTheseEqualHeight(selector) {
var these = $(selector);
if (these.length < 2) return;
these.height('auto');
var maxHeight = Math.max.apply(null, these.map(function(el) {
return $(this).height();
}));
these.height(maxHeight);
}