我对编程还是个新手,目前我遇到了一个问题。我使用了 W3schools 的代码,它允许我在匹配搜索结果时过滤表格。但是,我想让它对网站的用户来说更好。我想让他们能够通过搜索框进行搜索,并让他们可以选择从返回相同结果的框中选择下拉菜单。
下面是我用于 HTML 的代码:
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.."><table id="myTable">
<tr class="header">
<th style="width:60%;">Fruit Name</th>
<th style="width:40%;">Place of Origin</th>
</tr>
<tr>
<td>Apple</td>
<td>Asia</td>
</tr>
<tr>
<td>Black Berry</td>
<td>North America</td>
</tr>
<tr>
<td>Durian</td>
<td>SouthEast Asia</td>
</tr>
<tr>
<td>Watermelon</td>
<td>South Korea</td>
</tr></table>
以及使用的 JavaScript:
<script>
function myFunction() {
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
我很抱歉弄得一团糟,简而言之,这些是从 W3school 网站上获取的,并做了一些更改。如果可能的话,我想用搜索框实现一个下拉菜单,而不是只有一个搜索框。任何帮助将不胜感激。
最佳答案
根据您的评论,下面是更新后的代码,其中包含搜索框以及用于过滤行的下拉列表:
function myFunction(searchTerm) {
var input, filter, table, tr, td, i;
filter = searchTerm.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
var options = $("#fruitOptions");
$("#myTable tr:not(.header)").each(function() {
options.append($("<option />").val($(this).find("td:first-child").text()).text($(this).find("td:first-child").text()));
});
$("#myInput").on('input', function() {
myFunction($(this).val());
});
$("#fruitOptions").on('change', function() {
myFunction($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="myInput" placeholder="Search for names..">
<select id="fruitOptions">
<option value=''>- Please select -</option></select>
<table id="myTable">
<tr class="header">
<th style="width:60%;">Fruit Name</th>
<th style="width:40%;">Place of Origin</th>
</tr>
<tr>
<td>Apple</td>
<td>Asia</td>
</tr>
<tr>
<td>Black Berry</td>
<td>North America</td>
</tr>
<tr>
<td>Durian</td>
<td>SouthEast Asia</td>
</tr>
<tr>
<td>Watermelon</td>
<td>South Korea</td>
</tr>
</table>
关于javascript - 如何有一个过滤表格结果的下拉搜索框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47259288/