开发者

Taking attributes and using the as styles with jquery .each()

i guess this is a pretty simple question.

I want to give my li-tags a width that matches the image thats is inside it. So far i am getting my image-attributes right for each one.

$("#slider1 li img").each(function(){
 var imageWidth = $(this).width();
 var imageHeight = $(this).height();    
 $(this).attr('width', imageWidth);
 $(this).attr('height', imageHeight);
});

But i can't seem to figure out how i transfer the imageWidth to my li-tag. I tried with:

$("#slider1 li").css("width", imageWidth);

But that just renders the same width for all the li's.

Thanks for helping out :)

EDIT: My markup:

<ul id="slider1"> 
<li><img src="tester.jpg"/></li> 
<li><img src="tester2.jpg"/></li> 
<li><img src="tester3.jpg"/></li>开发者_StackOverflow; 
<li><img src="tester4.jpg"/></li> 
<li><img src="tester.jpg"/></li> 
<li><img src="tester2.jpg"/></li>
</ul> 


You can directly call just the parent li that contains the img element like this:

$(this).parent('li').css('width',imageWidth);

Note: this only works if the img is only one level deep under the li. Otherwise, use .closest('li') instead. parent will only traverse one level up, where as closest will keep traversing the DOM tree until it finds the element specified.


You should do:

 $(this).closest('li').css("width", imageWidth);

like this

$("#slider1 li img").each(function(){
 var imageWidth = $(this).width();
 var imageHeight = $(this).height();    
 $(this).attr('width', imageWidth);
 $(this).attr('height', imageHeight);
 $(this).closest('li').css("width", imageWidth);
});


$("#slider1 li img").each(function(){
    var imageWidth = $(this).width();
    var imageHeight = $(this).height();    
    $(this).parent().attr('width', imageWidth);
    $(this).parent().attr('height', imageHeight);
});


That's because the selector you're using for setting your '#slider1 li' width is setting them all at the same time (to whatever the last imageWidth was). You need to only set the .parent() width.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜