簡體   English   中英

<span>使用 jQuery</span>將特定文本字符串包裝在 HTML 標簽內

[英]Wrap a particular text string inside an HTML tag with a <span> using jQuery

我試圖用span將給定 HTML 標簽的文本內容中的某個單詞(甚至單詞的一部分)包裝起來,使用 jQuery 或普通 javascript 對其應用 class。

我只選擇了包含所需單詞/字符串的完整標簽,但我不知道如何 select 並將單詞包裝在其中。 我找到的所有方法都會搜索 substring,但總是搜索 select 並包裝整個標簽或其完整內容(例如wrapInner() ),這不是我想要的。

 $('h3:contains(icular)').wrap("<span class='highlight'></span>");
 .highlight { color: green; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h3>This is the first of several h3 headings</h3> <h3>This is another h3 heading, containing a particular word</h3> <h3>This is another h3 heading</h3> <h3>This is another h3 heading, again containing a particular word</h3> <h3>This is the way it should look: part<span class="highlight">iculär</span> word</h3> <p>This is ap tag, containing the same particular word/string. It should not be affected in this process.</p>

您可以使用.each()迭代所有包含您要查找的單詞的元素,然后對每個元素的 html 執行.replaceAll()

 const search = 'icular' $('h3:contains(' + search + ')').each( function(index, element) { $(element).html( $(element).html().replaceAll(search, '<span class="highlight">' + search + '</span>') ) })
 .highlight { color: green; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h3>This is the first of several h3 headings</h3> <h3>This is another h3 heading, containing a particular word and another instance of the same "particular" word</h3> <h3>This is another h3 heading</h3> <h3>This is another h3 heading, again containing a particular word</h3> <h3>This is the way it should look: part<span class="highlight">iculär</span> word</h3>

暫無
暫無

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

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