2011-06-16 65 views
0

我想檢查一個元素是否在其中沒有hrefs(即它是空的),如果是,就隱藏與它關聯的標籤。頁面上會有幾個元素需要檢查,如果它們是空的,所以我需要編寫一個循環。我需要幫忙寫循環。這裏是我的代碼到目前爲止:用JQUERY寫一個循環

if(jQuery('span.tags').is(':empty')) { 
     jQuery('span.label').hide()   
    }; 

請有人可以幫我這個代碼?

這是我的HTML

<div class="entry-meta"> 
      <span class="label">Tagged:</span> 
      <span class="tags"> 
      <a href="#" rel="tag">Career change</a>, 
      <a href="#" rel="tag">career change e course</a>, 
      <a href="#" rel="tag">career help</a> 
      </span> 
    </div><!-- END .entry-meta --> 

謝謝大家誰回答了這個帖子。這是有效的解決方案。

//Removes word 'Tagged:' if there are no tags 
jQuery('span.tags:empty').prev('span.label').hide(); 
+3

你能告訴我們你會使用這個代碼一些HTML。 – 2011-06-16 09:45:57

+0

[如何在jQuery中執行「For」循環?](http://stackoverflow.com/questions/5287669/how-to-perform-a-for-loop-in-jquery) – 2011-06-16 09:46:26

+0

for the loop ,請檢查jQuery中的.each方法 – Locksfree 2011-06-16 09:48:10

回答

1

您可以通過DOM元素使用eachfunction循環,和隱藏各一個。

$('span.tags:empty').each(function(i, value) { 
    $('span.label').hide(); 
}); 
+0

謝謝,喬希,我試過了,但它刪除了span.label,即使它們不是空的。 – madameFerry 2011-06-16 09:59:15

+0

查看我的回答@madameFerry – Alex 2011-06-16 10:04:24

+0

@madame:因爲'$('span.label')'選擇每個'span.label'元素。見@ richardneililagan的答案。 – 2011-06-16 10:06:20

1

基於您的HTML,即使不拋出顯式循環,您也應該能夠關閉此功能。

// something like 
$('span.tags').not(':has(a[href])') 
       .prev('span.label') 
       .hide() 
       ; 
+0

謝謝理查德,但這不起作用。即使元素爲空,我仍然可以看到Tagged:標籤。 – madameFerry 2011-06-16 10:14:02

+0

你記得把你的jQuery代碼放在'$(document).ready()'處理程序中嗎?最糟糕的是 – 2011-06-16 12:38:59

+0

。性能。碼。 EVER! – 2017-05-22 21:29:07

0

你不應該需要一個循環。基於這樣的假設:如果沒有標籤的tags跨度將是空的,這將做到這一點:

$('span.tags:empty').prev('span.label').hide(); 

Demo on jsfiddle

+0

簡單,整潔,快速。 – 2017-05-22 21:30:28