因此,我一直试图在找不到搜索结果时显示一条消息,我已经尝试了其他线程,但效果不佳,将不胜感激,谢谢。
到目前为止,这是我的代码:
$(document).ready(function(){
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myDIV *").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
});
});
});
#txt{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Filter Anything</h2>
<p>Type something in the input field to search for a specific text inside the div element with id="myDIV":</p>
<input id="myInput" type="text" placeholder="Search..">
<div id="myDIV">
<p>I am a paragraph.</p>
<div>I am a div element inside div.</div>
<button>I am a button</button>
<button>Another button</button>
<p>Another paragraph.</p>
<p id="txt">Nothing found</p>
</div>
答案 0 :(得分:1)
您可以将一个类添加到可搜索的元素中,并检查其中是否有:visisble
以确定是否应显示或隐藏#txt
。
$(document).ready(function() {
$("#myInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myDIV .item").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
$(".item:visible").length == 0 ? $('#txt').show() : $('#txt').hide();
});
});
#txt {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Filter Anything</h2>
<p>Type something in the input field to search for a specific text inside the div element with id="myDIV":</p>
<input id="myInput" type="text" placeholder="Search..">
<div id="myDIV">
<p class="item">I am a paragraph.</p>
<div class="item">I am a div element inside div.</div>
<button class="item">I am a button</button>
<button class="item">Another button</button>
<p class="item">Another paragraph.</p>
<p id="txt">Nothing found</p>
</div>