admin管理员组文章数量:1426058
I am having an annoying bug that I forgot why it happens:
I have an ordinary html list
<ul> <li>Some text</li> <li>Another Text </li> <li>text</li> <li>another one</li> </ul>
and I am trying to measure each li width
I was trying to write this jQuery code:
for (var i=0; i++; i <4)
{
$("ul li")[i].width();
}
but somehow that doesn't work - what am I doing wrong in this sentence $("ul li")[i].width();
?
I am having an annoying bug that I forgot why it happens:
I have an ordinary html list
<ul> <li>Some text</li> <li>Another Text </li> <li>text</li> <li>another one</li> </ul>
and I am trying to measure each li width
I was trying to write this jQuery code:
for (var i=0; i++; i <4)
{
$("ul li")[i].width();
}
but somehow that doesn't work - what am I doing wrong in this sentence $("ul li")[i].width();
?
- what do you expect to happen? – Alessandro Pezzato Commented Nov 28, 2011 at 13:23
- what is it that you are expecting? – Arindam Commented Nov 28, 2011 at 13:23
- I want to check the width of each <li> element - assuming each one has different text size – Alon Commented Nov 28, 2011 at 13:23
6 Answers
Reset to default 3$('ul li').each(function(){
/*width*/
console.log( $(this).width());
/*width+padding*/
console.log( $(this).outerWidth(true));
});
$('ul li').each(function()
{
$(this).width();
});
This is far more simple to walk over a set of elements with the .each()
function.
For use in a custom loop, you need to use the .eq()
method (and you should cache the list of element, instead of re-searching for all of them)
var li_elements = $("ul li");
for(var i=0, len = li_elements.length; i<len; i++) {
var elementWidth = li_elements.eq(i).width();
// do what you need with it..
}
or you can use the .each()
to iterate over the list
$("ul li").each(function(){
var elementWidth = $(this).width();
// do what you need with it..
})
$("ul li")[i]
is returning you a DOM element, not a jQuery object. Use:
var elements = $("ul li");
elements.each(function(){
//do something with $(this).width()
});
Note also, using the selector once outside the loop and them iterating over it, rather than repeating the selection every time.
When you use an indexer with a jquery object, you get the DOM elements.
try:
var $items = $("ul li");
for (var i=0; i < 4; i++)
{
$items.eq(i).width();
}
Accessing array items on jQuery objects will return you the actual DOM object, not the one wrapped with jQuery's sugar. Use $(...).eq(0).width()
instead.
Also, you can just use the each()
method to iterate over all the items instead of a for
loop, which is much easier, nicer-looking and elegant IMHO.
本文标签: javascriptHow to measure an elements width with jQueryStack Overflow
版权声明:本文标题:javascript - How to measure an elements width with jQuery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745393491a2656708.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论