Generate search links for comma separated words

2019-09-05 18:08发布

问题:

as always, your help is very much valued <3

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>

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?

回答1:

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>


回答2:

**Check this out. If the alert msg that you see is what you are looking for than you just need to append it in the div. http://jsfiddle.net/UH5U9/3/

EDIT

$('.tags').each(function(){
var s = $(this).html()

a = s.split(',');      
var temp='';      
for (var i = 0; i < a.length; i++)
{
    temp =temp + '<a href="oursite.com/search?query='+a[i]+'">'+a[i]+'</a>';

 }
$(this).html('');
$(this).html(temp);
});