Set background based on SPAN contents
I need to set a different background image dependant on the contents of a SPAN:
<div class="replies">
<span>2</span>
</div>
If SPAN = 1 background-image: url('reply.png') no-repeat;
If SPAN = 'anything other than 1'开发者_StackOverflow background-image: url('replies.png') no-repeat;
Can this be done in jQuery?
should be easy going
$(document).ready(function(){
var span = $('.replies').find('span').text();
if(span === '1')
$(this).css('background-image', 'url(\'reply.png\') no-repeat');
else
$(this).css('background-image', 'url(\'replies.png\') no-repeat');
});
Yes, you can loop through the elements, get the span inside and check the contents:
$(function(){
$('.replies').each(function(){
var img = 'replies.png';
if ($(this).find('span').text() == '1') {
img = 'reply.png';
}
$(this).css('background-image', 'url(' + img + ') no-repeat');
});
});
Take
$("div.replies > span").text()
and check that aginst "1"
var spanText = $("div.replies > span").text();
if ( spanText === "1" )
{
// change bg image
}
else
{
// another bg image
}
精彩评论