为逗号分隔的单词生成搜索链接 [英] Generate search links for comma separated words

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

问题描述

与往常一样,您的帮助非常重要< 3

as always, your help is very much valued <3

我的网站上列出了描述中包含元数据关键字的列表。我想让它们看起来像标签(我们的cms不支持标签因此这个hack)。它只打印用逗号分隔的单词,如下所示:

I have listings on my site that feature metadata keywords in the description. I'd like to make these appear like tags (our cms doesn't support tags hence this hack). It prints just the words separated with commas, like so:

<div class="tags">abp, accredited building practitioners, calendar of events, upcoming events</div>

javascript是否能够在这些div中找到任何单词并将其替换为链接到myite的href。 com / search?query = THEWORD?如果是这样,有没有人有他们可以共享的脚本?

Is javascript capable of finding any word in these divs and replacing them with a href that links to oursite.com/search?query=THEWORD ? If so, does anyone have a script they can share?

推荐答案

这是一个用jQuery构建的工作函数,虽然很容易可以转换为基本JavaScript:

Here is a working function built with a little jQuery, although easily can be converted to basic JavaScript:

jQuery:

<script>
    $(function(){
        $('.tags').each(function(){
            var obj=$(this),tags=obj.text().split(','),i=0,len=tags.length;
            if(obj.text()) {
                for(i;i<len;i++) {
                    var tag=tags[i].replace(/(^\s*)|(\s*$)/g,'');
                    tags[i]='<a href="http://oursite.com/search?query='+encodeURIComponent(tag)+'">'+tag+'</a>';
                }
                obj.html(tags.join(', '));
            }
        });
    });
</script>

HTML:

<div class="tags">abp, accredited building practitioners, calendar of events, upcoming events</div>
<div class="tags">test, another test, some more testing, etc</div>
<div class="tags">the, code, needed, to, be , in, an, each(), loop</div>
<div class="tags"></div>
<div class="tags">random, words, that, show, work, hopefully</div>
<div class="tags">the, return, false, was, causing, problems</div>
<div class="tags"></div>

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

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