开发者

jQuery - Using :contains for instant search with nested divs/classes?

I have a search box. I'm using jQuery and keyup to filter repeating divs.

Each div looks like this:

<div class="searchCell" id="searchCell' . $id . '">';
    <div class="friendName">
        // someNameOutputWithPHP.
        </div>
</div>

Now, I want to filter based on the name text. If someNameOutputWithPHP contains the search query, the entire searchCell should show(). If it doesn't, the entire searchCell should hide().

This doesn't work, though:

<script type="text/javascript">
$(document).ready(function() {
    $("#searchbox").keyup(function() {
        var searchValue = $(this).val();
        if(searchValue === "") {
            $(".searchCell").show();
            return;
        }
        $(".searchCell").hide();
        $(".searchCell > .friendName:contains(" + searchValue + ")").show();
    }); 
}); 
</script>


EDIT

New problem: I got the divs show() to show how I want.开发者_Python百科 But the :contains isn't working exactly right.

For instance: say one of the name's is Ryan. When I search for 'Ryan', I get nothing. But when I search for 'yan' I get the Ryan div.

What's wrong?

Here's the :contains code:

        $(".friendName:contains(" + searchValue + ")").parent().show();


That is because you are hiding the .searchCell and then showing its children .friendName divs, which though get display property will not show up because parent is hidden.

Try this:

<script type="text/javascript">
$(document).ready(function() {
    $("#searchbox").keyup(function() {
        var searchValue = $(this).val();
        if(searchValue === "") {
            $(".searchCell").show();
            return;
        }
        $(".searchCell").hide();
        //$(".searchCell:has(.friendName:contains(" + searchValue + "))").show();
        // OR
         //$(".friendName:contains(" + searchValue + ")").parents(".searchCell").show();
        // OR
          $(".friendName:contains(" + searchValue + ")").parent().show(); // If .searchCell is always a direct parent
    }); 
}); 
</script>


Your selector

$(".searchCell > .friendName:contains(" + searchValue + ")")

will select all .friendName divs that contain the text from searchValue. That works just fine, but you need to .show() the parent element. Just invoke the .parent() method for that:

    $(".searchCell > .friendName:contains(" + searchValue + ")").parent().show();

Demo: http://jsfiddle.net/d3ays/3/

And by the way, you HTML markup looks messed up too. There is a ; behind your div.searchCell for instance.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜