我有以下代码搜索页面上的文本并过滤结果:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="searchbox">
<div class="searchParent">
<span class="searchMe">A</span>
<span class="searchMe">1</span>
</div>
<div class="searchParent">
<span class="searchMe">B</span>
<span class="searchMe">2</span>
</div>
<div class="searchParent">
<span class="searchMe">C</span>
<span class="searchMe">3</span>
</div>
.searchMe
如何将类添加到找到文本的parent()
容器中?
我已尝试使用match()
,但由于 when: inventory_hostname in groups['groupname']
的结果返回字符串本身,而不是包含它的元素,因此不起作用。有什么建议吗?
答案 0 :(得分:1)
您可以改用.filter()
。
$('#searchbox').on('input', function() {
var searchWord = $('#searchbox').val().toUpperCase();
$('.searchParent').each(function() {
var par = $(this);
$(this).find('.searchMe').removeClass('found').filter(function(){
return searchWord != '' && $(this).text().toUpperCase().match(searchWord);
}).addClass('found');
});
});
.found{color: green;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="searchbox">
<div class="searchParent">
<span class="searchMe">A</span>
<span class="searchMe">1</span>
</div>
<div class="searchParent">
<span class="searchMe">B</span>
<span class="searchMe">2</span>
</div>
<div class="searchParent">
<span class="searchMe">C</span>
<span class="searchMe">3</span>
</div>
答案 1 :(得分:1)
试试这个:
$('#searchbox').on('input', function() {
var searchWord = $('#searchbox').val().toUpperCase();
$('.searchParent').each(function() {
var par = $(this);
if ($(this).find('.searchMe').text().toUpperCase().match(searchWord) || searchWord == '') {
$(par).fadeIn();
$(this).find('.searchMe').addClass('found');
if(searchWord == '') {
$(this).find('.searchMe').removeClass('found');
}
} else {
$(par).fadeOut();
console.log(2)
}
});
});
.found{
color:red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="searchbox">
<div class="searchParent">
<span class="searchMe">A</span>
<span class="searchMe">1</span>
</div>
<div class="searchParent">
<span class="searchMe">B</span>
<span class="searchMe">2</span>
</div>
<div class="searchParent">
<span class="searchMe">2</span>
<span class="searchMe">3</span>
</div>