2013-11-15 72 views
0

我正在開發一家咖啡店產品網站。我們有一個區域,每個產品都有一個咖啡強度指示器。數據庫根據強度是強,中,弱還是不適用來生成一個值。不適用於非咖啡產品。如果顯示n/a值,隱藏DIV

如果顯示n/a,我想隱藏包含div。

我到目前爲止的代碼如下。我有一些JavaScript代替了數據庫顯示的文本和強度指標的圖片。

如果span標籤中的咖啡強度不是我想隱藏的。

這可能嗎?

在此先感謝。

<div class="coffee-strength"> 
      <p>Coffee Strength: <span><?php echo $_product->getAttributeText('coffeestrength'); ?></span></p> 
</div> 



<script type="text/javascript"> 

      jQuery(function ($) { 
       $('.coffee-strength p span').each(function() { 
        var string = $.trim($(this).text()); 
        $(this).html('<img src="/images/' + string + '.png" alt="' + string + '" />'); 
       }); 

      }); 

</script> 
+1

也許你可以添加這個'<?PHP的echo $ _product-> getAttributeText( 'coffeestrength');在div的類中,就像JS中的那樣,你可以檢查這個類來隱藏它。 – Franck

回答

0
  jQuery(function ($) { 
      $('.coffee-strength p span').each(function() { 
       var string = $.trim($(this).text()); 
       if(string!="n/a"){ 
        $(this).html('<img src="/images/' + string + '.png" alt="' + string + '" />'); 
       }else{ 
        $(this).hide();  
       } 
       }); 

     }); 
2

這應該工作:

jQuery(function ($) { 
    $('.coffee-strength p span').each(function() { 
     var string = $.trim($(this).text()); 

     if (string == "n/a") 
      $(this).closest('.coffee-strength').hide(); 
     else 
      $(this).html('<img src="/images/' + string + '.png" alt="' + string + '" />'); 
    }); 
}); 
+0

我會推薦更可讀的'.closest('。coffee-strength')'而不是'.parent()。parent()' – Tomas

+0

@Tomas很好。剛更新了答案。 – melancia

0

更新後的腳本:

<script type="text/javascript"> 

      jQuery(function ($) { 
       $('.coffee-strength p span').each(function() { 
        var string = $.trim($(this).text()); 
        if(string!="22"){ 
         $(this).html('<img src="/images/' + string + '.png" alt="' + string + '" />'); 
        }else{ 
         $(this).closest('.coffee-strength').hide();  
        } 
        }); 

      }); 

      </script> 
0

你有很多方法可以這樣:

HTML代碼:

<div class="coffee-strength"> 
    <p>Coffee Strength: <span>Strong</span></p> 
</div> 
<div class="coffee-strength"> 
    <p>Coffee Strength: <span>Dim</span></p> 
</div> 
<div class="coffee-strength"> 
    <p>Coffee Strength: <span>n/a</span></p> 
</div> 

jQuery代碼:

$(function ($) { 
    $('.coffee-strength p span').each(function() { 
     var string = $.trim($(this).text()); 
     if (string == 'n/a') { 
      $(this).parent().hide(); 
     } 
    }); 
}); 

// or 

$(function ($) { 
    $('.coffee-strength p span:contains("n/a")').parent().hide(); 
});