下面是基於與id=test
/* array of words to highlight */
var words = ['dummy', 'survived', 'desktop'];
$(function() {
/* get html containing words to highlight*/
var wordsHtml = $('#test').html();
$.each(words, function(idx, word) {
var reg = new RegExp(word, 'g');
/* replace word with a span containing word ,use css to "highlight" class*/
wordsHtml = wordsHtml.replace(reg, '<span class="highlight">' + word + '</span>');
});
/* replace old html with new*/
$('#test').html(wordsHtml);
})
DEMO替換某些HTML段落的解決方案:http://jsfiddle.net/pjBuY/
你看?有一個非常好的(語法高亮)用Javascript編寫,不難找到。哦,看看這個,搜索'syntax highlighter',它是列表中的第一個。 –
我用這個正則表達式看起來好像更容易,如果你可以直接定位段落或div。 http://stackoverflow.com/questions/119441/highlight-a-word-with-jquery – Ekim
我只想使用jQuery,因爲我正在學習它。 – unknownsatan