gpt4 book ai didi

javascript - Console.log 在 if 语句中触发,但其余代码不会

转载 作者:行者123 更新时间:2023-12-02 23:52:58 26 4
gpt4 key购买 nike

我试图隐藏 $("#shop-subcategories-menu")当 #filter 输入中有某些内容(文本)时,并在为空时将其切换回可见状态。我不明白为什么 console.log(true)触发并返回 true 但 $("#shop-subcategories-menu").toggle(true);不触发。

如果我写$("#shop-subcategories-menu").toggle(true);直接进入控制台,div 切换回可见状态。

我显然错过了一些东西,但我看不到什么,请帮忙。

长话短说:如何制作<div id="shop-subcategories-menu">TEST</div> <input id="filter" type="text" placeholder="Search.."> 时切换可见是空的?

$(document).ready(function(){
$(document).on('keyup', '#filter', function (e) {
if ($(this).val() === '') {
console.log(true);
$("#shop-subcategories-menu").toggle(true);
}
var value = $(this).val().toLowerCase();
$("#myTable tr").filter(function () {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
$("#shop-subcategories-menu").toggle(false);
});
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}

td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}

tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body>

<div id="shop-subcategories-menu">TEST</div>
<p>Type something in the input field to search the table for first names, last names or emails:</p>
<input id="filter" type="text" placeholder="Search..">
<br><br>

<table>
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody id="myTable">
<tr>
<td>John</td>
<td>Doe</td>
<td>john@example.com</td>
</tr>
<tr>
<td>Mary</td>
<td>Moe</td>
<td>mary@mail.com</td>
</tr>
<tr>
<td>July</td>
<td>Dooley</td>
<td>july@greatstuff.com</td>
</tr>
<tr>
<td>Anja</td>
<td>Ravendale</td>
<td>a_r@test.com</td>
</tr>
</tbody>
</table>


</body>
</html>

最佳答案

您不需要输入 true,因为 toggle() 的作用与当前元素状态完全相反。

(如果显示则隐藏,如果隐藏则显示)

或者:

只需使用 jQuery 的 hide()show() https://www.w3schools.com/jquery/jquery_hide_show.asp

完全控制

更新答案。

您仍然需要处理当它不为空时发生的情况

在你的函数中做类似的事情:

if ($(this).val() === '') {
console.log(true);
$("#shop-subcategories-menu").hide();
} else {
$("#shop-subcategories-menu").show();
}

关于javascript - Console.log 在 if 语句中触发,但其余代码不会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55559746/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com