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

时间:2015-10-05 19:44:23

标签: javascript jquery html

我开始学习Jquery,我试图搜索一个叫做问题的表的所有列。目前它只搜索列" 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');
});
}

1 个答案:

答案 0 :(得分:0)

您可以使用$.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;
});