开发者

jQuery how to specify an existing selector

How do I do a selection on a existing selection in jQuery? This is the given HTML

<div id='search'>
    <form action='' method='GET'>
        <input id="searchbutton" type='submit' name='qs' value='search'>
            <div id="searchoptions">
                <input type="checkbox" checked="checked" id="search_books book" name="search_books" value="1" /><label for="search_books">book</label>
                <input type="checkbox" checked="checked" id="search_movies movie" name="search_movies" value="1" /><label for="search_movies">movies</label>
            </div>
    </form>
</div>

The jQuery part:

$('#search').each(function(){
    //do stuff
    $(this).click(function(){
        alert('checkbox clicked');
    });
});

Of curse the click function triggers if the div gets clicked. But I'd like it to g开发者_高级运维et triggered if the checkbox is clicked. I could just do $('#search input:checkbox') but I need to do some stuff with #search first. So how to I append a selector to $(this)?

e.g. $(this'input:checkbox')

Sorry if it's a fools question.


You would use .find() in this case, for example:

$(this).find(':checkbox');
//equiavlent to $('#search :checkbox')

There are many other tree traversal methods like this as well.

You can also do: $(':checkbox', this) but that's really just converted to the above by jQuery under the covers, so better to do it yourself IMO.


Use .find().

On another note, there's no reason to use .each() on $('#search') because that selector will only ever return 1 element, since HTML element IDs must be unique.


Define a variable to contain your result set.

var $myVar = $('#search');

Then use the .add() method.

$myVar = $myVar.add($('#search input:checkbox'));
$myVar.click(function(){
    alert('div or checkbox clicked');
});


You can use

$(":checkbox", $(this));

where the second parameter is the context on which to search for elements which match the selector.

So

$(":checkbox", $(this)).click(function(){
    alert('checkbox clicked');
});


use your parent() and children() methods. You can specify selectors as arguments.

$(this).children(':checkbox');
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜