javascript - Jquery Keyup 过滤器和输入值问题
问题描述
我正在用 jquery 在表中搜索。使用键盘搜索有效,但使用按钮过滤不起作用 请点击按钮。
我希望在单击按钮时将其添加到输入和搜索中
样本:
/* Searching with keyboard */
$(document).ready(function(){
$("#search").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("table td").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
/*Searching with button */
$("button").click(function(){
var id = $(this).attr("data-id");
$("#search").val(id);
});
table tr td{
border:1px solid #000;
}
<input type="text" id="search" placeholder="Search"><br>
<button type="button" data-id=""> Facebook</button>
<button type="button" data-id=""> Facebook</button>
<p>Searching with keyboard is working but filtering with button does not work. <br>Please click to button.</p>
<table>
<thead>
<tr>
<td>Hood 1</td>
<td>Hood 2</td>
</tr>
</thead>
<tbody>
<tr>
<td> Facebook</td>
<td> Facebook</td>
</tr>
<tr>
<td> Twitter</td>
<td> Twitter</td>
</tr>
</tbody>
</table>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
解决方案
您在单击按钮时缺少搜索关键字功能的调用
/* Searching with keyboard */
$(document).ready(function(){
$("#search").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("table td").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
/*Searching with button */
$("button").click(function(){
var id = $(this).attr("data-id");
$("#search").val(id);
$('#search').keyup();
});
table tr td{
border:1px solid #000;
}
<input type="text" id="search" placeholder="Search"><br>
<button type="button" data-id=""> Facebook</button>
<button type="button" data-id=""> Twitter</button>
<p>Searching with keyboard is working but filtering with button does not work. <br>Please click to button.</p>
<table>
<thead>
<tr>
<td>Hood 1</td>
<td>Hood 2</td>
</tr>
</thead>
<tbody>
<tr>
<td> Facebook</td>
<td> Facebook</td>
</tr>
<tr>
<td> Twitter</td>
<td> Twitter</td>
</tr>
</tbody>
</table>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
推荐阅读
- python - 使用python查找图像中黑色/灰色像素的所有坐标
- c++ - 放置/分段语法是否可能导致惰性“运算符或”重载?
- gradle - 如何让 Intellij IDEA 使用并行和 gradle 构建缓存进行构建
- c - C 中声明 char * VS (char *)
- windows - 如何在 Windows 上安装 selenoid?
- python - 使用函数返回名称后如何重用名称?
- r - 在R中连接数据框的每个元素
- mysql - 在 MySQL 中,如何修改 Partitioning 定义?
- gcc - 针对 ARM A7 故障优化 GCC 输出
- java - java.lang.NullPointerException:尝试从空对象引用上的字段“java.lang.String com.example.g.Model.PersonalShopper.ps_name”读取