【问题标题】:Add <a> to every word inside <h3>将 <a> 添加到 <h3> 中的每个单词
【发布时间】:2015-10-20 20:51:45
【问题描述】:

我想将 添加到 中的每个单词。该链接应包含它所环绕的单词。该网页有许多不同的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 会好!

【问题讨论】:

    标签: javascript php jquery


    【解决方案1】:
    1. 你可以使用html()和回调函数来更新值

    2. 要使用锚标记更新它,请使用 replace()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 实体,请尝试此代码

    $('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>

    【讨论】:

    • 好极了!谢谢!只有一个小问题它删除 & 并放置 &而是。
    • @Algatella : 很高兴为您提供帮助 :)
    • 你能告诉我如何处理特殊字符吗? =)
    【解决方案2】:

    给定答案中的代码不适用于嵌入式标签和 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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多