Jquery -使用grep搜索表的所有列
Jquery - Using grep to search all columns of a table?
我开始学习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;
});
相关文章:
- 如何使用提交按钮搜索表中的记录
- 展开表使用复选框
- 如何重置搜索表单中的特定表单元素
- 在网站上提交搜索表单以刮表
- 在导航栏中的搜索表单上使用jQuery for Action Listeners
- 如何将数据从一个表导入另一个表(使用数组)
- 如何将搜索表单仅添加到商店页面和类别页面
- 当至少有20个搜索结果时,只呈现10个搜索结果?使用Google Places API
- Wordpress:提交后,我如何在搜索表单中保留市场复选框
- Jquery搜索表可以'找不到带括号的单词
- 在搜索表单中,替换空格或仅使用正则表达式的隐词和数字
- 使用多个输入php-mysql自动完成搜索表单
- 使用javascript自定义搜索表单(如stackoverflow)
- Jquery -使用grep搜索表的所有列
- 使用js搜索表
- 使用javascript/jQuery搜索表,并返回正确的表行按钮点击和'Search '酒吧
- 表-使用jQuery进行实时搜索
- 如何使用jquery和razor制作搜索表单
- 抓取URL参数以使用jQuery或javascript维护搜索表单选项
- 数据表-使用重音中和的单个列搜索