2015-07-05 42 views
3

我正在開發Chrome擴展並嘗試隱藏頁面的一部分。我對這個東西相當陌生,所以如果我使用錯誤的術語,或者問題顯而易見的話,我會提前道歉!使用Javascript/JQuery隱藏文本

頁面格式如下圖所示:

<div class="wrapper"> 
    <span class="loud" style="text-decoration: none;">...</span> 
    <div class="leave-gap">...</div> 
    <quote>...</quote> 
    "*** I can't figure how to hide this ***" 
    <p></p> 
    <span id="id_12345" class="none">...</span> 
    <div class="block-footer">...</div> 
    <div class="leave-gap">...</div> 
</div> 

隨着片段所暗示的,我無法弄清楚如何隱藏星星位突出。

我有一個函數,它作爲輸入變量,在課堂上「包裝」的第一個元素:

function processComment(commentStart) 
{ 
    $element = commentStart; 

    while($element) 
    { 
     if(some condition) 
     { 
      $element.hide(); 
     } 
     $element.next(); 
    } 

因爲這段文字是由本身的任何標籤外坐着,它沒有被拾起。我不能隱藏整個包裝類,因爲它裏面有一些我需要顯示的位。

任何建議感激地收到。

感謝, 理查德

+1

感謝您的答覆。我喜歡Pranav解決方案的優雅。 – Richard

回答

1

設置可視性propery或包裝作爲摺疊,並設置兒童的可見性以覆蓋可視性屬性。它只會隱藏文本節點。

$('.wrapper').css('visibility', 'collapse').find('*').css('visibility', 'visible');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div class="wrapper"> 
 
    <span class="loud" style="text-decoration: none;">...</span> 
 
    <div class="leave-gap">...</div> 
 
    <quote>...</quote> 
 
    "*** I can't figure how to hide this ***" 
 
    <p></p> 
 
    <span id="id_12345" class="none">...</span> 
 
    <div class="block-footer">...</div> 
 
    <div class="leave-gap">...</div> 
 
</div>

+0

謝謝Pranav。這是一個很好的解決方案。在我的情況下,我可以寫: – Richard

+1

$ element.parent().css('visibility','collapse')。find('*').css('visibility','visible'); – Richard

+0

@Richard:很高興幫助:) –

0

你最好的選擇可能是你想隱藏到它自己的跨度內容放置。

+1

感謝Tozer,我無法控制內容的格式,但是如果我這樣做,你的建議就會起作用。 – Richard

0

如果我也明白了,你的if (some condition)是關於自身的文本內容,所以這是一個正則表達式的東西或喜歡的東西。

所以你可以做的是,找到涉及的文本部分,把它包裝在<span>標籤之間:那麼你可以用通常的方式來解決這個<span>元素。

它可能看起來像這樣(這裏假設你的薈萃例如意味着$element s爲連續的字):

function processComment(comment) { 
    // (comment is supposed to be the HTML element to process) 
    var words = $(comment).html().split(' '); 
    for (var i in words) { 
     var word = words|i]; 
     if(some condition on word) { 
      words[i] = '<span class="hidden-word">' + word + '</span>'; 
     } 
    } 
    $(comment).html(words.join(' ')); 
}