2013-08-26 135 views
0

我使用以下代碼示例的組合來更改background-image css值,具體取決於單獨的元素是否包含文本字符串。使用jQuery更改元素的背景圖像不會採取

單獨的元素多次出現在頁面上(WordPress的後期元數據),所以這個jQuery應該在每次符合條件時運行。

$(window).load(function(){ 
if ($(".postmetadata").contains("Seattle")) { 
     $(this).closest(".boxy").find(".storyNoIMG") 
     .addClass('.seattleIMG'); 
    } else { 
    } 
}); 

這裏是我使用的第二個例子:

  var imageURL = "images/seattle.png"; 

      if ($(".postmetadata").contains("Seattle")) { 
       $(this).closest(".boxy").find(".storyNoIMG") 
       .css("background-image","url(" + "images/seattle.png" + ")"); 
      } 

下面是HTML背景:

 <div class="boxy"> 
      <div class="boxGrad"> 

       <div class="postmetadata"> 
        <?php echo time_ago(); ?> • 
        <?php the_category(' • ') ?> 
       </div> 
       <div class="articleTitle"> 
        <a><?php the_title(); ?></a> 
       </div> 
       <div class="exPand"> 
       </div> 
      <div class="rightCtrls"> 

       <!-- heart + --> 
       <?php echo getPostLikeLink(get_the_ID());?> 
        <div class="imageGlass"> 
         <a href="#"> 
          <img src="<?php echo get_template_directory_uri(); ?>/media/imageMag-02.png"> 
         </a> 
        </div> 
       </div> 

      </div> <!-- end post right controls -->     
       <div class="ajaxBoxLoadSource"> 
        <iframe class="ajaxIframe"></iframe> 
       </div> 
       <div class="storyNoImg"></div> 
      <div class="articleImageThumb"> 
       <a href="<?php if(get_post_meta($post->ID, "url", true)) echo get_post_meta($post->ID, "url", true); else the_permalink(); ?>" rel="<?php the_ID(); ?>"> 
        <?php echo get_the_post_thumbnail($page->ID, 'original'); ?> 
       </a> 
      </div> 
     </div> <!-- end boxy --> 
+1

jQuery對象不具備的時候'contains'你不使用點方法,它支持':contains'選擇器。 – undefined

回答

2

我想這是你想要做什麼:

$(".postmetadata:contains('Seattle')").each(function(){ 
    $(this).closest(".boxy").find(".storyNoImg").css("background-image","url(" + "images/seattle.png" + ")"); 
}); 

首先你過濾你需要的元素,那麼你遍歷他們each()

而且因爲它已經注意到,有一個爲jQuery的對象沒有方法和添加類

+1

'

'和'.find(「。storyNoIMG」)'不匹配 –

+0

@ᾠῗᵲᄐᶌ對,很好,更新了答案 –

+0

選擇器!這工作完美無瑕。現在得到'<?php echo get_template_directory_uri(); ?>到'var'中... – canacast