好的,我已经使用下面的答案和评论中的改进代码更新了这个问题,并且与真实项目更相似。但它仍然无法在 IE8 中运行。 fiddle here
<ul id="definitions">
<li id="defid63">keyword1<input type="hidden" value="63" /></li>
<li id="defid61">keyword2<input type="hidden" value="61" /></li>
<li id="defid62">Keyword3<input type="hidden" value="62" /></li>
</ul>
<div id="html">Lorem ipsum keyword1 dolor keyword2 sit keyword3 amet, consectetur adipisicing elit, sed do eiusmod tempor</div>
我有一个关键字列表 ( ul > li
),并且有一个包含一些文本的字符串。我想用 <a>
包装每个出现的关键字。 -标签。我的代码在 Firefox 和 Chrome 中运行良好,但 IE(8) 与正则表达式不匹配。
jQuery(function($) {
// created by Gracenotes
// http://goo.gl/MTkcY
RegExp.quote = function(str) {
return str.replace(/([.?*+^$[\]\\(){}-])/g, "\\$1");
};
var $node = $('#html'),
// the dom element
html = $node.html(); // the text we'll manipulate
$('#definitions li').each(function() {
var defid = $(this).find('input').val(),
deftext = $(this).html().split("<input")[0],
//the keyword
//pattern = eval('/\\b('+RegExp.quote(deftext)+')\\b/gi');
pattern = new RegExp('\\b(' + RegExp.quote(deftext) + ')\\b', 'gi');
html = html.replace(pattern, '<a href="#id=' + defid + '">$1</a>');
});
// replace the dom content with our updated text
$node.html(html);
});
最佳答案
关于javascript - 正则表达式替换在 IE 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8053386/