Auto-hyperlink every occurence of a certain word (or word sequence) to predefined URL (non-ambiguous); but not show full URL

こ雲淡風輕ζ 提交于 2019-12-03 22:14:07

Starting with the question you linked, it's pretty easy to modify it to achieve your goal. So first assuming we have a list of phrase and links like this:

var words = [
    { word: 'foo', link: 'http://www.something.com' },
    { word: 'Something Else', link: 'http://www.something.com/else' ]
];

We can iterate over that list replacing any occurrence in the document, but including the word we are searching for in the text we are inserting. I've added in a tooltip to this too to show an example of what else you can do.

$(function() {
    $.each(words,
        function() {
            var searchWord = this.word;
            var link = this.link;
            $('body:contains("' + searchWord + '")').each(function() {
                var newHtml = $(this).html().replace(searchWord, 
                    '<a class="wikilink" title="here is a link to Wikipedia" href="'+link+'">' + searchWord + '</a>');
                $(this).html(newHtml);
            });
        }
    );
});

And a working example: http://jsfiddle.net/yxhk1fcd/10/

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