添加 <a><h3>里面的每一个字 [英] Add <a> to every word inside <h3>

查看:22
本文介绍了添加 <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!

推荐答案

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

要使用锚标记更新它,请使用 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>

这篇关于添加 &amp;lt;a&gt;&amp;lt;h3&gt;里面的每一个字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆