Javascript搜索栏只搜索标题

时间:2017-02-01 12:18:26

标签: javascript search hide

我如何只搜索b标签,而不是整个div。 现在我可以搜索整个div,但我只想搜索b标签中的标题。如果列表中有名称,则必须将其删除 HTML:

<div class="row">
    <div class="col-md-3">
    <div class="panel panel-default" id="list">
        <div class="panel-header">
            <div class="input-group">
                <input type="text" class="form-control" placeholder="Search for users" id="searchName"/>
                <div class="input-group-btn">
                    <div class="btn-group">
                        <button type="button" class="btn btn-primary">
                            <span class="glyphicon glyphicon-search"></span></button>
                    </div>
                </div>
            </div>
        </div>
        <div class="panel-body" id="user1">
            <div class="row">
                <div class="col-md-4">
                    <img src="" class="img-thumbnail">
                </div>
                <div class="col-md-8">
                    <b>Pieter</b><br>
                    (Laatste bericht)<br>
                    <i>12:01</i>
                </div>
            </div>
        </div>
        <div class="panel-body" id="user2">
            <div class="row">
                <div class="col-md-4">
                    <img src="" class="img-thumbnail">
                </div>
                <div class="col-md-8">
                    <b>Karel</b><br>
                    (Laatste bericht)<br>
                    <i>11:15</i>
                </div>
            </div>
        </div>
        <div class="panel-body" id="user3">
            <div class="row">
                <div class="col-md-4">
                    <img src="" class="img-thumbnail">
                </div>
                <div class="col-md-8">
                    <b>Pilot</b><br>
                    (Laatste bericht)<br>
                    <i>9:36</i>
                </div>
            </div>
        </div>
    </div>
</div>

Javascript:

function contains(text_one, text_two){
    if (text_one.indexOf(text_two) != -1){
        return true;
    }
}

$("#searchName").keyup(function () {
    var searchName = $("#searchName").val().toLowerCase();
    $(".panel-body").each(function () {
        if(!contains($(this).text().toLowerCase(), searchName)) {
            $(this).hide();
        }
        else {
            $(this).show();
        }
    });
});

1 个答案:

答案 0 :(得分:2)

在条件中使用find()专注于元素的子B标记:

在:

if(!contains($(this).text().toLowerCase(), searchName)) {

后:

if(!contains($(this).find('b').text().toLowerCase(), searchName)) {