根据SPAN内容设置背景

时间:2010-06-10 08:11:08

标签: jquery

我需要根据SPAN的内容设置不同的背景图像:

<div class="replies">
<span>2</span>
</div>

如果SPAN = 1 background-image:url('reply.png')no-repeat;

如果SPAN ='除1以外的任何内容'background-image:url('replies.png')no-repeat;

这可以在jQuery中完成吗?

3 个答案:

答案 0 :(得分:1)

应该很容易

$(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');
});

答案 1 :(得分:0)

$("div.replies > span").text()并检查“1”

var spanText = $("div.replies > span").text();

if ( spanText === "1" )
{
    // change bg image
}
else
{
    // another bg image
}

答案 2 :(得分:0)

是的,您可以循环遍历元素,获取内部范围并检查内容:

$(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');
  });
});
相关问题