簡體   English   中英

添加<a>到里面的每個單詞</a> <h3>

[英]Add <a> to every word inside <h3>

我想在<“h3”>中的每個單詞中添加<“a”>。 該鏈接應包含它已被包裹的單詞。 該網頁有許多不同的h3。

<h3>add links</h3>
<h3>to each word</h3>

結果應如下所示:

<h3><a href="add">add</a> <a href="links">links</a></h3>
<h3><a href="to">to</a> <a href="each">each</a> <a href="word">word</a></h3>

我不知道是否可能(或好)使用PHP其他jQuery / JS會很好!

  1. 您可以使用html()函數的html()來更新值

  2. 要使用錨標記更新它,請使用帶有regex replace()

 $('h3').html(function(i, v) { return v.replace(/(\\s*)(\\w+)(\\s*)/g, '$1<a href="$2">$2</a>$3'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <h3>add links</h3> <h3>to each word</h3> 

要避免編碼的html實體,請嘗試此代碼

 $('h3').html(function() { return $(this).text().replace(/(\\s*)(\\w+)(\\s*)/g, '$1<a href="$2">$2</a>$3'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <h3>add links</h3> <h3>to each word</h3> 

給定答案的代碼不適用於嵌入式標簽和Unicode字。

這是一個更好的萬無一失的替代品:

 $('h3').contents().filter(function() { return this.nodeType === 3; }).replaceWith(function() { return this.nodeValue.replace(/(\\S+)(?=\\s+|$)/g, '<a href="$&">$&</a>'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <h3>add links to each word</h3> <h3>with Юникод support & <i>ignoring</i> <em>this</em></h3> 

暫無
暫無

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

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