2011-11-01 25 views
0

我們有一張桌子,可以進行高級搜索。我想讓表格突出顯示他們搜索的每個詞彙表中的文字。例如:如果他們在「主題」字段中搜索特定單詞,則只應在「主題」列中突出顯示該術語,即使該單詞可能出現在另一列中。更高效的方式使用jQuery在每個表格行中根據條件查找第n個單元格?

我使用.highlight()方法的突出顯示插件 - 但我最擔心的是選擇合適的表格單元格的有效方法。我有什麼作品,但它有幾百行很慢。我覺得沒有.each()循環,有更好的方法來做到這一點。

//Select the table 
var $table = $("#myTable"); 

//Examples: The users' search terms 
var sFrom = "example"; 
var sTo = "example"; 
var sSubject = "example"; 

//Make sure there is at least 1 term to search for 
if(sFrom !== "" || sTo !== "" || sSubject !== ""){ 

    //Find the index of each column based on a class set on the table header 
    //(the number of columns could change from page to page) 
    var $headers = $table.find("thead tr").children(); 
    var iFrom = $headers.filter(".js-from").index(); 
    var iTo = $headers.filter(".js-to").index(); 
    var iSubject = $headers.filter(".js-subject").index(); 

    //---------------------------------------------- 
    //This is the critical part! 
    //---------------------------------------------- 
    //Loop through each table row and select each 
    $table.find("tbody tr").each(function (i, row) { 
     var $thisRowCells = $(row).children(); 
     if (sFrom !== "") $thisRowCells.eq(iFrom).highlight(sFrom); 
     if (sTo !== "") $thisRowCells.eq(iTo).highlight(sTo); 
     if (sSubject !== "") $thisRowCells.eq(iSubject).highlight(sSubject); 
    }); 
    //---------------------------------------------- 
} 

編輯: 這裏是上面代碼的的jsfiddle嘗試:http://jsfiddle.net/ZLTdf/1/

+0

是否有可能需要優化'.highlight()'方法呢? – Blazemonger

+0

這是可能的,但它是一個相當快的現狀。你可以看看我從這裏得到的頁面:http://jobs.http.edu/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html –

+1

O'Reilly的「jQuery Cookbook」建議用普通的for循環替換'.each()'會帶來一些優化(p.112)。 – Blazemonger

回答

0

我不認爲有任何方式,以避免循環,但你可以修剪下來的堆棧的大小在你做之前。喜歡的東西:

var input = $(e.currentTarget), 
    index = input.parent().index(), 
    needle = input.val().toLowerCase(), 
    haystack = $("td:nth-child(" + (index+1) + ")"); 

haystack.each(function() { 
    var td = $(this); 

    if(td.text().toLowerCase().indexOf(needle) != -1) 
     td.highlight(needle); 
    else 
     td.highlight(needle); 

}); 

(我在http://jsfiddle.net/nicholasstephan/84DK9/有一個向上的jsfiddle)

可能會更好地工作......

+0

我不確定這是否會起作用,因爲除了我們正在搜索的單元之外還有其他單元。看看我放在一起的這個jsfiddle,我可能應該把它放在首位。 http://jsfiddle.net/ZLTdf/ –

2

這似乎爲我工作,約2倍比.each()循環更快當定時。我能夠在〜200ms內突出顯示3列獨立字符串,用於500行中的500行

var $headers = $table.find("thead th"); 
var iFrom = $headers.filter(".js-from").index()+1; 
var iTo = $headers.filter(".js-to").index()+1; 
var iSubject = $headers.filter(".js-subject").index()+1; 

if (sFrom!== "") $table.find("tr td:nth-child("+iFrom+")").highlight(sFrom); 
if (sTo!== "") $table.find("tr td:nth-child("+iTo+")").highlight(sTo); 
if (sSubject!== "") $table.find("tr td:nth-child("+iSubject+")").highlight(sSubject); 

這可以根本改進嗎?

相關問題