正确使用jquery在列表和子列表中进行搜索 [英] Getting the jquery right to do a search in lists and sublists

查看:64
本文介绍了正确使用jquery在列表和子列表中进行搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法在任务栏中设置搜索输入以在菜单中隐藏和显示元素.我想设置一个jQuery函数,该函数会自动循环通过我的第一个列表,并且如果存在输入(#search-bar)中输入的字符串,则将"active"类添加到#thomas或#thierry(请查看代码)在子列表的某个项目中.

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.

我的HTML基本上是这样的,关于如何编写脚本的任何想法?

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>

推荐答案

您没有得到像$('#search-bar').text()这样的输入值;应该更改为$('#search-bar').val();

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

更改为

var str = $('#search-bar').val();
  $("ul li:contains("+str+")").addClass("active");

尝试使用输入,就像mouseup事件

try use input it is like mouseup event

 $('#search-bar').on("input", function () {
    var str = this.value.trim();

    $("ul li:contains(" + str + ")").addClass("active");
});

这篇关于正确使用jquery在列表和子列表中进行搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆