我是jQuery的新手,在搜索表中用户输入的元素时需要帮助。我是用JS编写的,但是在使用jQuery编写时遇到了问题。
找到该元素后,表中具有相同类名的其他行应可见,其他行应隐藏:
$(document).ready(function()
{
search(".site-table", "#recordInput");
console.log("Document is ready");
}
);
function search(search_table, search_field)
{
// Searching for an item specified in search_field within a table
$(search_field).on("keyup", function()
{
var target_text = $(this).val().toLowerCase();
//Hide everything first
$(search_table).find('tr').addClass(".hidden");
$(search_table).find('tr').each(function(index, element){
// For each row, find out if the row has the target_text in it
$element:contains($target_text).each(function(index, element){
$(element).removeClass(".hidden");
});
// for each row with the target text in it, find other rows with this rows class name in their class name and show them. Any other row should be hidden
});
感谢您的帮助。
编辑1:
因此,这是注释后的编辑代码。我仍然无法正常工作:
$(document).ready(function()
{
search(".site-table", "#recordInput");
console.log("Document is ready");
}
);
function search($search_table, $search_field)
{
console.log("Starting to search...");
$($search_field).on("keyup", function()
{
// Heighlight the search field
$(this).css('border', '1px solid red');
$search_text = $(this).val().toLowerCase();
// 1st method:
$search_result = $($search_table).find('tbody tr').text().toLowerCase().indexOf($search_text > -1); // Does not work! Nothing is found when there is a match
console.log("Search Result: ", $search_result);
// 2nd method:
$($search_table).find('tr').each(function(index, element){
// For each row, toggle the hidden class if the row contains the search text
$(this).toggleClass('hidden', $(this).text().toLowerCase().indexOf($search_text > -1));
});
// 3rd method:
var found = $($search_table).find('tbody tr').filter(function() {
return $(this).text().toLowerCase() == $search_text;
});
console.log("found: ", found);
});
}
这些方法都不起作用!每种方法我在做错什么?
答案 0 :(得分:1)
您的问题与使用indexOf
有关。您必须放在括号之间的只是搜索文本,> -1
必须在外面。查看此示例:
var its_ok = $('div').first().html().indexOf('b') > -1
console.log('first one: ', its_ok)
var its_not_ok = $('div').first().html().indexOf('b' > -1)
console.log('second one: ', its_not_ok)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>abcd</div>
您所做的是第二种方法,它不是使用indexOf
的正确方法。