2017-03-16 23 views
1

我有一個HTML表格看起來返回另一列如下圖所示:如何搭配jQuery中一列文本匹配和匹配的行

enter image description here

是有辦法找出根據菜品名稱到其類別。 僅基於<td>文字? 例如:輸出將是 海鮮:扇貝在黃油和醬油,蝦大蒜黃油等。 飲料:旭硝子,可樂等.... 謝謝...

+0

是的,我相信這是可能的,但沒有向我們展示你所努力的嘗試也讓我們來幫助你任何進一步的 –

+0

我認爲filter()方法會幫助我,但無法正確使用它。它看起來像「jQuery數據表」搜索.. –

回答

0

以下功能需要你列數想要匹配,應該匹配的文本以及匹配返回值必須返回的returnColumn。

columnMatch:列號你要尋找的文本
matchText:文字要匹配
returnColumn:從中要從如果匹配的話

返回文本列號
function getMatchesFromTable(matchColumn,matchText,returnColumn) 
    { 
     var matchedValues = []; 
     $("table tr td:nth-child("+matchColumn+")").each(function() { 
       if($(this).text() == matchText){ 
        matchedValues.push($(this).parent().find('td:nth-child('+returnColumn+')').text()); 
       } 
     }); 

     return matchedValues; 

    } 

例爲你的情況,你可以撥打:

getMatchesFromTable(3,"Seafood",5); 

這將返回類別爲海鮮的所有元素的數組

我試圖編寫一個通用函數來匹配所有用例。仍然可以根據您的要求進行更多擴展,例如在匹配行中返回多個列,匹配大小寫不敏感等。您可以修改此基本函數以向其添加更多功能。

+0

試圖瞭解這個 –

+1

感謝得到它......作品像一個魅力。 –

+0

歡迎傢伙!! – abhinsit

0

試試這個

var array = [];  

var headers = []; 
$('table th').each(function(index, item) { 
    headers[index] = $(item).html(); 
}); 
$('table tr').has('td').each(function() { 

    var arrayItem = {}; 
    $('td', $(this)).each(function(index, item) { 
     arrayItem[headers[index]] = $(item).html(); 
    }); 
    array.push(arrayItem); 
});  
alert(JSON.stringify(array)); 

$(array).each(function(index, item) { 
    if ($.inArray("find", item) > -1){ 
      alert('found'); 
    } 
}); 

,或者您可以使用

$('table tr').has('td').each(function(index, td) { 
    var tableRow = td.filter(function() { 
     return $(this).text() == "foo"; 
    }).closest("tr"); 
});