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>
The result should look like this:
<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>
I don't know if it's possible (or good) to use PHP else jQuery/JS would be good!
答案 0 :(得分:2)
您可以使用带有回调函数的html()
更新值
要使用锚标记进行更新,请使用replace()
regex
醇>
$('h3').html(function(i, v) {
return v.replace(/(\s*)(\w+)(\s*)/g, '$1<a href="$2">$2</a>$3');
});
&#13;
<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>
&#13;
要避免编码的html实体,请尝试使用此代码
$('h3').html(function() {
return $(this).text().replace(/(\s*)(\w+)(\s*)/g, '$1<a href="$2">$2</a>$3');
});
&#13;
<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>
&#13;
答案 1 :(得分:1)
来自给定答案的代码不能很好地使用嵌入式标签和Unicode字。
这是一个更好的万无一失的替代方案:
$('h3').contents().filter(function() {
return this.nodeType === 3;
}).replaceWith(function() {
return this.nodeValue.replace(/(\S+)(?=\s+|$)/g, '<a href="$&">$&</a>');
});
&#13;
<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>
&#13;