【发布时间】:2022-01-22 09:50:10
【问题描述】:
这两个示例中的hide()、show()和.addClass有什么区别,为什么.addClass在第二个示例中不起作用?
这两个示例是简单的 jQuery 搜索函数,它们使用 :contain 在 .record div 中查找搜索词。
此示例适用于 hide() 和 show()。
$(document).ready(function() {
$('#search').keyup(function() {
var text = $(this).val().toLowerCase();
$('.record').hide();
$('.record').each(function() {
if ($(this).text().toLowerCase().indexOf("" + text + "") != -1) {
$(this).closest('.record').show();
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Search <input type='text' id='search' placeholder='Search Text'>
<br /><br />
<div class="record">Now is the time for all good men to come to the aid of their city</div>
<div class="record">Now is the time for all good women to come to the aid of their country</div>
<div class="record">Now is the time for all droids to come to the aid of their universe</div>
<div class="record">Now is the time for all fluffy bears to come to the aid of their wilderness</div>
<div class="record">Now is the time for all short people to come to the aid of their county</div>
但是在下面的例子中我需要做的是
-
使用类
.display-none和.display-block,而不是 hide() 和 show(),因为我在另一个具有相同 .reason html 标记的 Javascript 函数中使用 hide() 和 show()。 -
与上面的示例不同,最初
display:none是所有 .record div,因此它们是隐藏的,并且仅在它们实际是搜索结果时与display:block一起显示。
$(document).ready(function() {
$('#search').keyup(function() {
var text = $(this).val().toLowerCase();
$('.record').addClass("display-none");
$('.record').each(function() {
if ($(this).text().toLowerCase().indexOf("" + text + "") != -1) {
$(this).closest('.record').addClass("display-block");
}
});
});
});
.display-block {
display: block !important;
}
.display-none {
display: none !important;
}
.record {
display: none !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Search <input type='text' id='search' placeholder='Search Text'>
<br /><br />
<div class="record">Now is the time for all good men to come to the aid of their city</div>
<div class="record">Now is the time for all good women to come to the aid of their country</div>
<div class="record">Now is the time for all droids to come to the aid of their universe</div>
<div class="record">Now is the time for all fluffy bears to come to the aid of their wilderness</div>
<div class="record">Now is the time for all short people to come to the aid of their county</div>
【问题讨论】:
-
Display-none 不是一个类它是一个样式
-
仅供参考:
"" + text + """"+和+""没用 -
删除类
.addClass("display-block").removeClass("display-none"); -
@epascarello 所以这个字符串对不区分大小写没有任何作用?
.addClass("display-block").removeClass("display-none");是什么意思? -
您正在向字符串添加一个空字符串。
console.log("" + "foo" + "" === "foo");零差别。
标签: javascript jquery