添加< a> < h3>中的每个单词 [英] Add <a> to every word inside <h3>
本文介绍了添加< a> < h3>中的每个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在<"h3">内的每个单词上添加<"a">.链接应包含已被环绕的单词.网页上有许多不同的h3.
I want to add <"a"> to every word inside an <"h3">. The link should contain the word it has been wrapped around. The web page has many different h3's.
<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会很好!
I don't know if it's possible (or good) to use PHP else jQuery/JS would be good!
推荐答案
-
您可以将
html()
与回调函数一起使用以更新值
You can use
html()
with callback function to update the value
要使用锚标记更新它,请使用replace()
和regex
For updating it with anchor tag use replace()
with regex
$('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实体,请尝试以下代码
To avoid encoded html entities try this code
$('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>
这篇关于添加< a> < h3>中的每个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文