Generate search links for comma separated words

一曲冷凌霜 提交于 2019-12-11 20:08:38

问题


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);
});


来源:https://stackoverflow.com/questions/10022781/generate-search-links-for-comma-separated-words

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