2014-12-22 24 views
0

的HTML代碼jQuery的隱藏<TD>如果他有一個 「」(空格,不 )

<table class="wrap_class_adv"> 
    <tr> 
     <td>321</td> 
     <td>123</td> 
     <td> </td> <--- HERE 
    </tr> 
</table> 

jQuery代碼

$('.wrap_class_adv tr').each(function() { 
    if ($(this).find('td').text() === " ") { 
     $(this).class('visibility', 'hidden'); 
    } 
}); 

http://jsfiddle.net/yeqgtb06/

如何隱藏TD包含使用可視性的空間:隱藏?

+1

根據downvoted的答案,請告訴我們,如果您的意思是(數字之一)空格或多個空格(一般意義上的a)? – reporter

回答

1

你忘了鏈接jQuery,比你試圖設置class,但設置css

見我的小提琴:

<table class="wrap_class_adv"> 
    <tr> 
     <td>321</td> 
     <td>123</td> 
     <td> </td> 
    </tr> 
</table> 

<script> 
$('.wrap_class_adv td').each(function() { 
    if ($(this).text() === " ") { 
     $(this).addClass('hidden'); 
    } 
}); 
</script> 

<style> 
    td {border:1px solid #000;} 
    .hidden {visibility: hidden;} 
</style> 

http://jsfiddle.net/yeqgtb06/26/

PS。不要忘記鏈接jQuery。

+2

可見性更好,顯示:沒有,你也必須擔心保留表格佈局,colspans等。 – dfsq

+0

@dfsq:你是對的,我更新了我的答案。 – panther

+0

@dfsq:在這種情況下,可能刪除'border'做同樣的事情,還是不行? – panther

0

如果你想隱藏包含一個空間中的任何元素,即使它包含其他文本,使用含有選擇,這樣

$("td:contains(' ')") 

如果要隱藏僅包含一個空格字符元素,你可能有將其全部選中,然後遍歷結果並檢查其內容:

$('td').each(function() { 
    if ($(this).html() == ' ') 
     $(this).css('visibility', 'hidden'); 
}); 
1

你是在正確的軌道上。對於每個tr,您試圖找到包含空格的td

你可以做的是,在td上做一個filter只返回那些包含空格的td,然後根據需要更改css

注意:如果有一個空格或多個空格,甚至沒有空格並且只是空的,則無關緊要。但是,如果有&nbsp;那麼它將不會像您在問題標題中提到的那樣受到影響。

$('.wrap_class_adv tr').each(function() { // for each tr 
 
    $(this).find("td").filter(function() { // filter td 
 
     return (this.innerText == "");  // whose innerText is empty 
 
    }).css('visibility', 'hidden');  // apply visibility to css 
 
});
td { border: 1px solid #000; padding: 4px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table class="wrap_class_adv"> 
 
    <tr> 
 
     <td>321</td> 
 
     <td>123</td> 
 
     <td> </td> <!-- One space --> 
 
     <td> </td> <!-- Three spaces --> 
 
     <td>&nbsp;</td> <!-- &nbsp; is visible --> 
 
    </tr> 
 
</table>

0

嘗試設置類TD:這裏

http://jsfiddle.net/elennaro/yeqgtb06/28/代碼做exactely你想要什麼隱藏TD,而不是TR

CSS:

td { 
border:1px solid #000; 
} 
.hidden { 
    display: none; 
} 

JS:

$(document).ready(function() { 
$('.wrap_class_adv tr').each(function() { 
    $(this).find('td').each(function() { 
     if($(this).text().trim() === "") 
     $(this).addClass('hidden'); 
    }); 
}); 
}); 
相關問題