添加<a> to every word inside </a> <h3> <a>

时间:2015-07-29 17:59:03

标签: javascript php jquery

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!

2 个答案:

答案 0 :(得分:2)

  1. 您可以使用带有回调函数的html()更新值

  2. 要使用锚标记进行更新,请使用replace()

  3. regex

    &#13;
    &#13;
    $('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;
    &#13;
    &#13;

    要避免编码的html实体,请尝试使用此代码

    &#13;
    &#13;
    $('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;
    &#13;
    &#13;

答案 1 :(得分:1)

来自给定答案的代码不能很好地使用嵌入式标签和Unicode字。

这是一个更好的万无一失的替代方案:

&#13;
&#13;
$('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;
&#13;
&#13;