我有两个 Select 输入和一个过滤一些div的搜索字段.select
个输入按预期工作.搜索域应该显示包含搜索框中的文本的div,但它只有在例如"ane"而不是"jane"时才起作用.
在座的有人能看到问题所在吗?
$(document).ready(function() {
// Hide all divs initially.
$('.col.kontaktpersoner').hide();
// Show the corresponding divs when the user types in the search field and selects a department and/or location.
$('#search-field, #departments, #locations').on('input change', function() {
var searchTerm = $('#search-field').val().toLowerCase().trim();
var department = $('#departments').val();
var location = $('#locations').val();
// Construct the selector for the corresponding divs.
var selector = '.col.kontaktpersoner';
if (department) {
selector += '.' + department;
}
if (location) {
selector += '.' + location;
}
// Find all divs that contain the search term.
var filteredDivs = $(selector).filter(':contains("' + searchTerm + '")');
// If there are no divs that contain the search term, then find all divs that contain the search term as a whole word.
if (filteredDivs.length === 0) {
filteredDivs = $(selector).filter(':contains(\\b' + searchTerm + '\\b)');
}
// If there are still no divs that contain the search term, then find all divs that contain the search term as a prefix.
if (filteredDivs.length === 0) {
filteredDivs = $(selector).filter(':contains("' + searchTerm + '%")');
}
// Show the filtered divs.
filteredDivs.show();
// Hide all other divs.
$('.col.kontaktpersoner').not(filteredDivs).hide();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="departments">
<option value="">Select Department</option>
<option value="sales">Sales</option>
<option value="marketing">Marketing</option>
<option value="engineering">Engineering</option>
</select>
<select id="locations">
<option value="">Select Location</option>
<option value="new york">New York</option>
<option value="london">London</option>
<option value="tokyo">Tokyo</option>
</select>
<input type="text" id="search-field" placeholder="Search kontaktpersoner...">
<div class="col kontaktpersoner sales london">
<p>John Doe</p>
</div>
<div class="col kontaktpersoner marketing london">
<p>Jane Doe</p>
</div>
<div class="col kontaktpersoner engineering london">
<p>Peter Parker</p>
</div>