如何将网站上的关键字转换为jQuery链接 [英] How to turn keyword on a site into links with jQuery

查看:63
本文介绍了如何将网站上的关键字转换为jQuery链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一组关键字转化为我网站上的链接.我目前正在使用此代码,它将一个关键字转换为链接.但是,现在我想将其扩展为几个单词.链接将始终相同,但是关键字会更改,因此链接文本也必须反映出这一点.

I'm trying to turn a set of keywords into links on my site. I am currently using this code which will turn one keyword into a link. However, now I want to expand it to have several words. The link will always be the same, however, the keyword changes, so the link text must also reflect that.

这是我当前正在使用的代码:

Here is the code I am currently using:

<script type="text/javascript">
(function($) {
  var thePage = $("body");
  thePage.html(thePage.html().replace(/Wedding Stationery/ig, '<a class="discrete" href="http://www.kateguest.com">wedding stationery</a>'));
})(jQuery)
</script>

如何将其扩展为使用5个或6个关键字?

How can I expand this to use 5 or 6 keywords?

推荐答案

循环执行替换.您可以在替换中使用$&来指代匹配的文本.

Do the replacement in a loop. You can use $& in the replacement to refer to the text that was matched.

var keywords = ['wedding stationery', 'something else', 'other keyword'];
var thePage = $("body");
var theHtml = thePage.html();
for (i = 0; i < keywords.length; i++) {
    theHtml = theHtml.replace(new RegExp(keywords[i], 'ig'),
                '<a class="discrete" href="http://www.kateguest.com">$&</a>');
}
thePage.html(theHtml);

演示

这篇关于如何将网站上的关键字转换为jQuery链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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