我們有一張桌子,可以進行高級搜索。我想讓表格突出顯示他們搜索的每個詞彙表中的文字。例如:如果他們在「主題」字段中搜索特定單詞,則只應在「主題」列中突出顯示該術語,即使該單詞可能出現在另一列中。更高效的方式使用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/
是否有可能需要優化'.highlight()'方法呢? – Blazemonger
這是可能的,但它是一個相當快的現狀。你可以看看我從這裏得到的頁面:http://jobs.http.edu/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html –
O'Reilly的「jQuery Cookbook」建議用普通的for循環替換'.each()'會帶來一些優化(p.112)。 – Blazemonger