Javascript 获取jQuery集中最宽的元素
假设我有一堆具有不同文本内容的Javascript 获取jQuery集中最宽的元素,javascript,jquery,css,Javascript,Jquery,Css,假设我有一堆具有不同文本内容的元素 如何获得最宽的 jQuery很好。我只关心确定跨度,而不关心宽度本身的值 类似的问题也在讨论中。但它们只得到宽度的值 我是这样开始的: $('span').each(function(id, value){ if ($(this).width() > w) { largestSpan = id; } }); 使用jQuery识别div中最宽的跨度: var oSpan; // Container object f
元素
如何获得最宽的
jQuery很好。我只关心确定跨度,而不关心宽度本身的值
类似的问题也在讨论中。但它们只得到宽度的值
我是这样开始的:
$('span').each(function(id, value){
if ($(this).width() > w) {
largestSpan = id;
}
});
使用jQuery识别div中最宽的跨度:
var oSpan; // Container object for loop item
var oWidest; // Container object for current widest in loop
var nWidth = 0; // Int to store current span width
var nWidest = 0; // Int to contain widest items width
var aWidest = []; // Array to contain multiple matching spans
// Call each function on spans within div
$('#divContainer span').each(function(nIndex)
{
// Set reference to current span to avoid multiple calls per iteration
oSpan = $(this);
// Set current width to avoid multiple calls per iteration
nSpanWidth = oSpan.width();
// Compare current width to widest width
if (nSpanWidth == nWidest)
{
// If exact,add to array and set current widest items
aWidest.push(oSpan);
oWidest = oSpan;
nWidest = nSpanWidth;
}
else if( nSpanWidth >= nWidest )
{
// If wider, reset array and set current widest item
oWidest = oSpan;
nWidest = nSpanWidth;
aWidest = [].push(oWidest)
}
else { } // Move along short stuff.
});
几乎完全相同的答案之间间隔一分钟。仅此一项就投了赞成票。这一项是两项中最优雅、最紧凑的一项这里唯一的抱怨是每次执行
$(this)
时都在创建一个新的jQuery对象。在循环中,效率确实很重要,所以最好只存储一次$element=$(此)
,然后每次引用$element
而不是$(此)
。@AlexKinnee是的,我同意此反馈。更新。再调整一次,您可以运行.width()一次并存储它,而不是运行两次。
var oSpan; // Container object for loop item
var oWidest; // Container object for current widest in loop
var nWidth = 0; // Int to store current span width
var nWidest = 0; // Int to contain widest items width
var aWidest = []; // Array to contain multiple matching spans
// Call each function on spans within div
$('#divContainer span').each(function(nIndex)
{
// Set reference to current span to avoid multiple calls per iteration
oSpan = $(this);
// Set current width to avoid multiple calls per iteration
nSpanWidth = oSpan.width();
// Compare current width to widest width
if (nSpanWidth == nWidest)
{
// If exact,add to array and set current widest items
aWidest.push(oSpan);
oWidest = oSpan;
nWidest = nSpanWidth;
}
else if( nSpanWidth >= nWidest )
{
// If wider, reset array and set current widest item
oWidest = oSpan;
nWidest = nSpanWidth;
aWidest = [].push(oWidest)
}
else { } // Move along short stuff.
});