I have multiple containers like this
<div class="container">
<span>
<!-- Inside the 开发者_如何学Gospan is either text or img -->
</span>
</div>
Goal is to have border around ".container span" only if it contains and image.
i tried something like this.. but it doesnt work
if( $(this).find('.container span img').is(":visible") ){ $(".container span").css({'border':'10px'}); }
visible
is a pseudo selector so it's
.is(':visible')
You can also use it like so
$(this).find('.container span img:visible')
EDIT
Hey, wait, are you saying that it might not contain an image at all? In that case, you don't want to be checking for visibility, but rather something like
$(this).find('.container span img').length > 0
(of course, if there might be images, and they might be hidden, you want to check the length of img:visible
)
EDIT 2
Now you've got a working check as to whether or not there is a visible image. The rest depends on your implementation. I assumed from the use of $(this)
that there will be a DOM node of some kind to search within, that'll only have one .container
for each value of this
.
If that's not the case - if you want to look at all of the DOM in one go - you could go about something like this:
$('.container span img:visible').each(function() {
$(this).closest('span').css('border', '10px');
});
Above, you're saying that "for all visible images inside a span inside a .container
, add a border to their parent spans.
Another way of doing it would be something like this:
$('.container span').filter(function() { return $(this).find('img:visible').length > 0; }).css('border', '10px');
You have two problems. First, your css is wrong. Your telling it to give it a 10px border of nothing. You need to specify what kind of border and probably the color.
Second, .is("visible")
should be .is(":visible")
Check out the working code on jsfiddle.net
(I had to remove the this
selector but you can modify your existing code to the above.)
jQuery(function(){
jQuery('.container').find('span').find('img').parents('span:first').css('boder','10px solid red');
});
http://jsfiddle.net/VMAJ7/1/
Is there a reason why you have the span
. You can apply the border directly to the image without the need for a span tag, specially if you are loading your images dynamically and your images have different dimensions. You then have to ensure your span tag is resized to match your image width and height. You can simplify things by getting rid of the span
tag, else if all your images have same dimensions, you need to specify your span width and height. Also don't forget to specify your border properties such as style and color.
var $cont = $('.container span');
var $cont1 = $('.container span img');
$cont.each(function() {
$cont.has('img').css({
'width': $cont1.width(),
'height': $cont1.height(),
'border': '10px solid red'
});
});
精彩评论