How to turn keyword on a site into links with jQuery

南楼画角 提交于 2020-01-11 11:48:12

问题


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>

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


回答1:


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);

DEMO




回答2:


I would suggest something like this:

var keywordsArray = ["place", "all", "of the", "keywords in here like this"];
var thePage = $("body");

for (var i = 0; i < keywordsArray.length; i++) {
    thePage.find(":contains("+keywordsArray[i]+")").each(function(){
        var _this = $(this);
        var content = _this.html();
        content.replace(keywordsArray[i], '<a href="discrete" href="http://whateveryouwant.com/">' + keywordsArray[i] + '</a>');

        _this.html(content);
    });
};


来源:https://stackoverflow.com/questions/17866866/how-to-turn-keyword-on-a-site-into-links-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!