Getting the jquery right to do a search in lists and sublists

人盡茶涼 提交于 2020-01-06 15:32:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!