2012-06-15 52 views
0

我試圖在使用jQuery的代碼片段中突出顯示變量和關鍵字。假設,我有一個Java代碼片斷這樣的,在jQuery中突出顯示變量和關鍵字

public class abc { 
    public static void main(String args[]) { 
    int count = 0; 

} 
} 

我使用的按鈕稱爲變量「變量」和「關鍵詞」保留關鍵字。 有沒有辦法呢?或者我應該使用正則表達式?

+1

你看?有一個非常好的(語法高亮)用Javascript編寫,不難找到。哦,看看這個,搜索'syntax highlighter',它是列表中的第一個。 –

+0

我用這個正則表達式看起來好像更容易,如果你可以直接定位段落或div。 http://stackoverflow.com/questions/119441/highlight-a-word-with-jquery – Ekim

+0

我只想使用jQuery,因爲我正在學習它。 – unknownsatan

回答

0

下面是基於與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/

相關問題