搜索单词,替换为链接 [英] Search For Words, Replace With Links

查看:118
本文介绍了搜索单词,替换为链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的数组

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

我希望它在页面上搜索单词并用链接替换它。这样做有效吗?似乎它可能是CPU饥饿。

I want it to search the page for word and replace it with link. Is there an efficent way of doing this? It seems it may be CPU hungry.

抱歉应该更多地宣传...

Sorry should have exlained more...

它会搜索每个例如,带有.message类的元素。然后查找其中的所有单词。

It would search each element with the class .message for instance. Then find all of the words within that.

此数组中还有几百个

推荐答案

给出一些内容,如:

    <div class="message">Somethsg1</div>
    <div class="message">Something</div>
    <div class="message">Ssething</div>
    <div class="message">Something Else</div>
    <div class="message">Something da</div>
    <div class="message">Somethin2g</div>

您可以使用以下内容:

//your array
var words = [
    {
        word: 'Something',
        link: 'http://www.something.com'
    },
    {
        word: 'Something Else',
        link: 'http://www.something.com/else'
    }
];
//iterate the array
$.each(words,
    function() {
        //find an element with class "message" that contains "word" (from array)
        $('.message:contains("' + this.word + '")')
             //substitute html with a nice anchor tag
             .html('<a href="' + this.link + '">' + this.link + '</a>');
    }
);

此解决方案虽然存在一个问题(在示例中也显示)。如果您搜索 Something 的示例并找到 Something beautiful ,则contains将匹配。

如果您想要严格选择,必须这样做:

This solution has one immediate problem though (showed in the example too). If you search for example for Something and you find Something beautiful, the "contains" will be match.
If you want a strict selection, you have to do:

//for each array element
$.each(words,
    function() {
        //store it ("this" is gonna become the dom element in the next function)
        var search = this;
        $('.message').each(
            function() {
                //if it's exactly the same
                if ($(this).text() === search.word) {
                    //do your magic tricks
                    $(this).html('<a href="' + search.link + '">' + search.link + '</a>');
                }
            }
        );
    }
);

您可以选择是先迭代所有数组元素,然后是所有dom,还是反过来。这也取决于你要搜索哪种单词(参见两个例子中的为什么)。

It's your choice whether to iterate all array elements first then all the doms, or the other way around. It's also depends on which kind of "words" you are gonna search (See the two example for the "why").

BIG警告:如果数组包含用户定义的内容,则必须先对其进行清理,然后再将其清除为元素'html!

BIG WARNING: if the array contains user-defined content, you have to sanitize it before injiecting it to the elements' html!

这篇关于搜索单词,替换为链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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