0

我想选择、突出显示并将匹配的字符串转换为链接。到目前为止,它可以在 jsFiddle 中找到。

但是当我尝试在 asp.net 网络表单中使用它时,相同的脚本会中断,我收到以下错误

SyntaxError: invalid quantifier
[Break On This Error]   

var pattern = new RegExp("("+this+")", ["gi"]);

实际代码

function HighlightKeywords(keywords)
{        
var el = $("#article-detail-desc");
$(keywords).each(function()
{
    var pattern = new RegExp("("+this+")", ["gi"]);
    var rs = "<a href='search.aspx?search=$1'<span style='background-color:#FFFF00;font-weight: bold;background-color:#FFFF00;'>$1</span></a>";
    el.html(el.html().replace(pattern, rs));
});
}       

HighlightKeywords(["got", "the","keywords", " tags " ]);

http://jsfiddle.net/LE3sg/6/

我不知道为什么我在 asp.net 网页表单页面中不断收到此错误

4

1 回答 1

1

When looping an array with jQuery each should always use the arguments in callback to access the array element and use $.each method as opposed to $(selector).each

$.each(keyowrds, function(index, item)
{
    var pattern = new RegExp("("+item+")", ["gi"]);

In code you are using if you log typeof this to console will find it is not actually a string

API reference: http://api.jquery.com/jQuery.each/

于 2013-04-07T11:53:10.923 回答