2011-11-22 54 views
0

在下面的腳本,我想強調所有的單詞在句子建議改善腳本

function SearchQueue(text) 
{ 
    if(text !== null) 
    { 
    text = text.replace(/「/g, "\""); 
    text = text.replace(/」/g, "\""); 
    text = text.replace(/’/g, "\'"); 
    text = text.replace(/‘/g, "\'"); 
    text = text.replace(/–/g, "\-"); 
    text = text.replace(/ +(?=)/g,''); 
    $.trim(text); 
    text = text.replace(/\d\.\s+|[a-z]\)\s+|•\s+|[A-Z]\.\s+|[IVX]+\.\s+/g, ""); 
    text = text.replace(/([0-9A-Z]+[.)]|•)\s+/gi, ""); 
    text = text.replace(/(\r\n|\n|\r)/gm," "); 
    } 
    var words = text.split(' '); 
    for(var i=0;i<words.length;i++) 
     $('*').highlight(''+words[i]+''); // Will highlight the script with background color 
} 

但是,這使我的頁面「反應遲鈍」。請建議我改進腳本...

+0

多少字呢?而且,空串不是必需的。 – Ryan

+0

計數會很高... – Exception

+2

'/ +(?=)/'的含義是什麼?一個或多個空間後跟一個空格?你可以用'/ + /'來簡化它,並用一個空格代替。 –

回答

2

您在每次迭代中選擇整個dom樹,這可能解釋爲無響應。 嘗試以下操作:

var body = $('body'); // since thats where all the text should live 
for(var i=0;i<words.length;i++){ 
    body.highlight(''+words[i]+''); // Will highlight the script with background color 
} 
+0

我會試一試..這是一個非常好的主意。 – Exception

+0

工作得很好謝謝 – Exception

1

您可以結合幾個使用匹配評價你取代了(不知道JavaScript調用他們什麼)。

例如:http://jsfiddle.net/zyqVE/

function match_eval(m){ 
    switch (m){ 
     case "「":case "」": 
      return "\""; 
     case "‘":case "’": 
      return "'"; 
     // etc... 

    } 
    return m; 
} 


alert("this 「i「 a test".replace(/[「「’‘–]/g, match_eval)); 

上下文:

function match_eval(m){ 
    switch (m){ 
     case "「":case "」": 
      return "\""; 
     case "‘":case "’": 
      return "'"; 
     case "–" 
      return "-"; 

    } 
    return m; 
} 

function SearchQueue(text) 
{ 
    if(text !== null) 
    { 
    text = text.replace(/[「」’‘–]/g, match_eval); 
    text = text.replace(/ +(?=)/g,''); 
    $.trim(text); 
    text = text.replace(/\d\.\s+|[a-z]\)\s+|•\s+|[A-Z]\.\s+|[IVX]+\.\s+/g, ""); 
    text = text.replace(/([0-9A-Z]+[.)]|•)\s+/gi, ""); 
    text = text.replace(/(\r\n|\n|\r)/gm," "); 
    } 
    var words = text.split(' '); 
    for(var i=0;i<words.length;i++) 
     $('*').highlight(''+words[i]+''); // Will highlight the script with background color 
} 
+0

看起來非常有趣......你能否在當前的功能中實現它。 – Exception

+0

非常感謝:-) – Exception

1

這是我的第一套調整:

var $all = $('*'); 

function SearchQueue(text) { 
    if(text) { 
     text = text.replace(/[「」]/g, '"'); 
     text = text.replace(/[’‘]/g, "'"); 
     text = text.replace(/–/g, '-'); 
     text = text.replace(/\s+/g, ' '); 
     $.trim(text); 
     text = text.replace(/\d\.\s+|[a-z]\)\s+|•\s+|[A-Z]\.\s+|[IVX]+\.\s+/g, ''); 
     text = text.replace(/([0-9A-Za-z]+[.)]|•)\s+/g, ''); 
     var words = text.split(' '); 
     for(var i = 0; i < words.length; i++) { 
      $all.highlight(words[i]); // Will highlight the script with background color 
     } 
    } 
} 
+0

非常感謝您的回答。 – Exception