简体   繁体   English

jQuery函数以链接标签替换匹配的标签/关键字

[英]jQuery Function to replace matching tags/keywords with a link tag

I need a functionality where i had to highlight/replace the matching tags/keywords for the main text of the article and turn those matching tag/keywords into link like one shown below 我需要一种功能,其中我必须突出显示/替换文章正文的匹配标签/关键字,然后将这些匹配标签/关键字转换为如下所示的链接

en/search.aspx?language=en-US&issue=1&pageID=2&search=Something

Below code which i am using works fine except that it even changes HTML if it matches the keyword. 我正在使用的以下代码工作正常,除了如果它与关键字匹配甚至可以更改HTML。

Logic for below code is simple i pass the array from code behind to jquery function in following format "[ 'one', 'two','three','US','UK' ]" 下面代码的逻辑很简单,我以以下格式"[ 'one', 'two','three','US','UK' ]"将数组从代码后面传递给jquery函数

in this case it will change the above link also as en- US matches one of the array element while looping through the contents N no of times 在这种情况下,它也会更改上述链接,因为en- US匹配数组元素之一,同时循环遍历内容N次

I would appreciate help in this regard so that function only changes the words not any matching part of word and ignore HTML tags while doing same 我希望在这方面有所帮助,以便函数仅更改单词,而不更改单词的任何匹配部分,并在执行相同操作时忽略HTML标签

PART OF CODE IS IN ASP.Net Format like <%= _pPID %>; 部分代码采用ASP.Net格式,例如<%= _pPID%>;

function HighlightKeywords(keywords)
{        
    var el = $("#article-detail-desc");
    var language = "<%= _planguage %>";
    var pid = <%= _pPID %>;
    var issueID = <%= _pIssue %>; 

    // array format = " 'one', 'two','three','US','UK' ";

    $(keywords).each(function()
    {
        var pattern = new RegExp("("+this+")", ["gi"]);
         var rs = "<a class='ad-keyword-selected' href='en/search.aspx?Language="+language+"&PageId="+pid+"&issue="+issueID+"&search=$1' title='Seach website for:  $1'><span style='color:#990044; tex-decoration:none;'>$1</span></a>";
        el.html(el.html().replace(pattern, rs));
    });
}   

HighlightKeywords([<%= _pKeywords %>]);


<div id="article-detail-desc">

all the text related to article will be show displayed inside this div and any matching words will be replaced by the link <a></a> 
</div>

You are passing a string and the function woks with arrays. 您正在传递一个字符串,并且该函数带有数组。

Try to use: 尝试使用:

// array format = ['one', 'two','three','US','UK'];

instead of 代替

// array format = " 'one', 'two','three','US','UK' ";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM