How to turn keyword on a site into links with jQuery

前端 未结 2 1933
-上瘾入骨i
-上瘾入骨i 2021-01-25 05:49

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 sev

相关标签:
2条回答
  • 2021-01-25 06:33

    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);
        });
    };
    
    0 讨论(0)
  • 2021-01-25 06:34

    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

    0 讨论(0)
提交回复
热议问题