Jquery -使用grep搜索表的所有列

Jquery - Using grep to search all columns of a table?

本文关键字:搜索表 使用 grep Jquery      更新时间:2023-09-26

我开始学习Jquery,我试图搜索一个名为questions的表的所有列。目前它只搜索列"q_text",但我想扩展它来检查q_options_1, q_options_2, q_options_3和q_options_4。我试着用了||运算符,但我不确定我把它放在了正确的位置。

下面是问题代码:

    //Adding the search functionality to our search button
    $('#search').on('click', findMatches);
    function findMatches(criteria){
    $("#questions tbody tr").remove(); 
    //Get the JSON data from our HTML and convert it to a JavaScript object
    //In the real world, this data will likely be retrieved  from the server via an AJAX request
    var questions = JSON.parse(document.getElementById('questions-json').innerHTML);
var results = $.grep(questions, function(x, i){
var index = x.q_text.indexOf($('#searchText').val()) 
return (index >= 0);
})
console.log(results);
 //Loop through the list array and create a table row for each item.
$.each(results, function(i, question) {
 var tblRow = '<tr>' +
'<td>' + question.id + '</td>' +
'<td>' + question.q_text + '</td>' +
'<td>' + question.q_options_1 + '</td>' +
'<td>' + question.q_options_2 + '</td>' +
'<td>' + question.q_options_3 + '</td>' +
'<td>' + question.q_options_4 + '</td>' +
'<td>' + question.q_correct_option + '</td>' +
'<td>' + question.q_difficulty_level + '</td>' +
'</tr>'
//Add our table row to the 'questions' <table>
$(tblRow).appendTo('#questions tbody');
});
}

您可以使用$.each在您的grep内循环遍历对象属性并测试每个

建议首先缓存$('#searchText').val()的值,这样就不需要每次迭代都进行dom搜索

var query = $('#searchText').val();
var results = $.grep(questions, function(x, i){
    var isMatch = false; 
     $.each(x, function(key, value){
        if( value.indexOf( query)>-1){
           isMatch = true;
           // break loop when match found
           return false;
        }
     });
     return isMatch;
});