簡體   English   中英

隱藏HTML div中的特定單詞而不會丟失樣式/格式

[英]Hiding specific words in HTML div without losing style/format

我想在HTML div中隱藏特定的單詞而不丟失javascript / jquery中的格式。 這是我嘗試過的方法,但與樣式/格式混淆。 HTML代碼:

  <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<div id="ctl00_ctl40_g_fa7fc6e0_693d_4dde_91fd_1dbe1d7d0e76_ctl00_ListForm2_formFiller_ctl02" 
class="summary">Count the number of texts:
<ul><li>Text 0</li>
<li>Text 1</li><li>Text 2</li>
<li>Text 3</li><li>Text 4</li>
<li>Text 5</li></ul>
</div>

JS代碼:

$(function() {
   $('.summary').each(function() {
   var $this = $(this);
 $this.html($this.text().replace(/\bCount \bthe \bnumber \bof \btexts\b/g, '<b>Texts:</b>'));
});

});

我還在這里創建了一個JSFiddle。 請先嘗試在沒有JS函數的情況下運行它,然后再與JS函數一起運行,以了解我的風格/格式。

這就是你想要的嗎?

$(function() {
  $('.summary').each(function() {
   var $this = $(this);
  $this.html($this.html().replace(/\bCount \bthe \bnumber \bof \btexts\b/g, '<b>Texts:</b>'));
  });

});

您應該替換html而不是文本節點。 http://jsfiddle.net/sLa3dkdd/1/

您只用更改的文本內容替換了html,因此保留了文本,但松散了所有html元素。 這樣,您可以保留html:

$this.html($this.html().replace(/\bCount \bthe \bnumber \bof \btexts\b/g, '<b>Texts:</b>'));

更好的方法是替換文本節點內容:

$('.summary').contents().first()[0].textContent='Texts:';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM