我有一个任务列表,我想为其创建搜索功能。我已经设法做到了,只要您开始输入,列表就会做出响应并隐藏所有不正确的结果。但是我仍然无法显示正确的结果。
代码如下
更新了正确的解决方案
HTML
<input type="text" id="search" placeholder="Player Search" />
<div id="todo">
<div class="task">Task 1</div>
<div class="task">Task 2</div>
<div class="task">Task 3</div>
</div>
Javascript
var $div = $("#todo")
var result;
$("#search").keyup(function() {
var val = $.trim(this.value).toUpperCase();
if (val === "")
$(".task").show()
else {
$(".task").hide()
result = $("#todo .task").filter(function() { //Updated to match child of id todo
return -1 != $(this).text().toUpperCase().indexOf(val)
}).show()
console.log(result)
$(".task").eq(result).show();
}
})
由于我才开始学习 javascript,如果您能解释我的错误,以及对答案/过程的外行逐步解释,我将不胜感激。
作为奖励,如果您还可以解释如何解决此类 JavaScript 问题以找到根本问题,我们将不胜感激。
最佳答案
var $div = $("#todo")
var result;
$("#search").keyup(function() {
var val = $.trim(this.value).toUpperCase();
if (val === "")
$div.show()
else {
$(".task").hide()
result = $("#todo .task").filter(function() { //Updated to match child of id todo
return -1 != $(this).text().toUpperCase().indexOf(val)
}).index()//get the index of the div that has match
console.log(result)
result != -1 ? $(".task").eq(result).show() : $(".task").hide()//show or hide div depending on matching index
}
})
- 始终记住,在同一上下文中ID 应始终是唯一的。
- 使用类来定位多个元素。
关于Javascript Keyup 搜索子 div 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37180525/