问题
I am having trouble setting up a search input into my taskbar to hide and display elements into my menu. I want to set up a jQuery function that automatically loops trough my first list and adds the class “active” to #thomas or #thierry (pls look at the code) if a string entered in the input (#search-bar) is present in some item in the sublist.
Basically my HTML looks like this, any ideas on how to write the script ?
<script type="javascript">
var str;
function searchT() {
str = $('#search-bar').text();
$("ul li:contains(str)).addClass("active");
}; </script>
<input id="search-bar" type="text" name="search" placeholder="Rechercher" class="form-control gbo-search-sidebar" />
<ul>
<li id="Thomas">
<span class="title">
Thomas
</span>
<ul class="sub-menu">
<li id="red">
<span class="title">
Red
</span>
</li>
<li id="orange">
<span class="title">
Orange
</span>
</li>
<li id="Green">
<span class="title">
Green
</span>
</a>
</li>
</ul>
</li>
<li class=" start" id="Thierry">
<span class="title">
Thierry
</span>
<ul class="sub-menu">
<li id="blue">
<span class="title">
Blue
</span>
</a>
</li>
</ul>
</li>
</ul>
回答1:
you did not get input value like this $('#search-bar').text()
; should change to $('#search-bar').val()
;
str = $('#search-bar').text(); // change to val();
$("ul li:contains(str)).addClass("active");
^^^^ you did not search text value ,actualy you are searching "str" string
Change to
var str = $('#search-bar').val();
$("ul li:contains("+str+")").addClass("active");
try use input it is like mouseup event
$('#search-bar').on("input", function () {
var str = this.value.trim();
$("ul li:contains(" + str + ")").addClass("active");
});
来源:https://stackoverflow.com/questions/24952587/getting-the-jquery-right-to-do-a-search-in-lists-and-sublists