javascript - 搜索过滤器上的 jquery - 换行
问题描述
这段代码工作正常,但问题是optgroup
好像没有找到结果option
,$.wrap()
但如果没有找到结果,我无法换行optgroup
。
$('.search').on('keyup keydown', function(){
searchFilter($(this).val());
});
function searchFilter(value){
$('option').each(function(){
if($(this).text().toLowerCase().indexOf(value.toLowerCase()) >= 0){
$(this).removeClass('hidden');
$(this).removeAttr('disabled');
if($(this).parent().is('span')){
$(this).unwrap('<span>');
}
}else{
$(this).addClass('hidden');
$(this).prop('disabled', true);
if(!$(this).parent().is('span')){
$(this).wrap('<span>');
}
}
});
}
.hidden{
display: none !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="search" />
<div class="row">
<select multiple style="width: 150px;height:200px" id="search">
<optgroup label="test01">
<option>car</option>
<option>bike</option>
<option>cycle</option>
</optgroup>
<optgroup label="test02">
<option>orange</option>
<option>apple</option>
<option>pineapple</option>
</optgroup>
</select>
</div>
解决方案
隐藏optgroups
并且options
可能不是要走的路,即使包装在span
. 当我在 Safari mobile 中测试时,包裹<span style="disaply:none">
不起作用。
您更好的选择是从下拉列表中删除您不想要的项目。在这样做时,您需要创建原始下拉列表的克隆,以便记录初始状态。
$(document).ready(function() {
//Add a hidden clone
var clone = $("#fancy").clone(true);
clone.attr("id", "fancy_clone");
clone.css("display", "none");
$("body").append(clone);
$('.search').on('keyup', function() {
searchFilter($(this).val());
});
function searchFilter(value) {
//Need a working clone - keep our clone as the original record
var workingClone = $("#fancy_clone").clone(true);
$("#fancy").empty();
//Remove unwanted options
$(workingClone).find("option").each(function() {
if ($(this).val().toLowerCase().indexOf(value.toLowerCase()) === -1) {
var thisParent = $(this).parents("optgroup");
$(this).remove();
//remove optgroup if it is empty
if ($(thisParent).children("option").length === 0) {
$(thisParent).remove();
}
}
});
//UPdate the actual select
$("#fancy").append($(workingClone).html());
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<input type="text" class="search" />
<select id="fancy">
<optgroup label="test01">
<option value="car">car</option>
<option value="bike">bike</option>
<option value="cycle">cycle</option>
</optgroup>
<optgroup label="test02">
<option value="orange">orange</option>
<option value="apple">apple</option>
<option value="pinapple">pineapple</option>
</optgroup>
</select>
推荐阅读
- android - Androidx 模块,android:attr/ttcIndex & android:attr/fontVariationSettings 未找到
- php - 在 XAMPP 上运行 Laravel 项目:“RouteCollection.php 第 179 行中的 NotFoundHttpException”
- oracle - 必须将此操作的 global_names 参数设置为 TRUE
- kotlin - Kotlin let vs != null
- javascript - 三个 JS 加载失败错误
- c++ - Linux getrusage() maxrss 最大驻留集大小不随分配增加(C++)
- c - 将字符串保存到动态列表中
- java - 将请求路径参数绑定到对象
- javascript - 如何在html中呈现多行字符串变量
- ios - 通过 safari 检查 PWA 是否添加到主屏幕