http://jsfiddle.net/nHGU6/
测试 HTML:
<div id="wrapper-accent-sensitive">
<p>咖啡厅</p>
<p>asdf</p>
<p>咖啡厅</p>
</div>
<hr />
<div id="wrapper-not-accent-sensitive">>
<p>咖啡厅</p>
<p>asdf</p>
<p>咖啡厅</p>
</div>
测试 CSS:
。黄色 {
背景颜色:#ffff00;
}
替换Javascript:
jQuery.fn.highlight = function (words, options) {
var accentedForms = {
'c': 'ç',
'e': 'é'
};
var settings = { className: 'highlight', element: 'span', caseSensitive: false, wordsOnly: false, accentInsensitive: false };
jQuery.extend(settings, options);
if (settings.accentInsensitive) {
for (var s in accentedForms) {
words = words.replace(s, '[' + s + accentedForms[s] + ']');
}
}
if (words.constructor === String) {
words = [words];
}
var flag = settings.caseSensitive ? "" : "i";
var pattern = "(" + words.join("|") + ")";
if (settings.wordsOnly) {
pattern = "\\b" + pattern + "\\b";
}
var re = new RegExp(pattern, flag);
return this.each(function () {
jQuery.highlight(this, re, settings.element, settings.className);
});
};
测试代码:
$(document).ready(function() {
$("#wrapper-accent-sensitive").highlight("cafe", { className: 'yellow' });
$("#wrapper-not-accent-sensitive").highlight("cafe", { className: 'yellow', accentInsensitive: true });
});