开发者

Jquery Selector Options

First post here so please be gentle :)

I searched all over the net and I'm not sure I'm searching by the right terms neither for its name. But what does the secondary options do in a jQuery selector? For example:

$('.results table', this.parent().prev())

The second lot of options on the .results table matches im not sure what this actually does? Is it similar to $('.results table').parent().prev() for example. Sorry I开发者_如何转开发 have just lifted this code as an example.

Appreciate the pointers as I'm just learning jQuery.


The second parameter is an optional context that you can provide to the constrain the selector to search for matches only in the provided context. For example, say you're looping through the <tr> elements of a <table> and in each <tr> element you want to select the second <td> element. You could use the following

$('table tr').each(function() {
    $('td:eq(1)', this).doSomething(); // the function context, this, is the `<tr>`
                                       // element in each iteration
});

The selectors documentation is really very good and worth perusing through. In fact, the whole of the jQuery API documentation is good :)


It means to look for the selector somewhere "underneath" the elements referred to by the second parameter. It's like:

$('secondParameterSelector').find('firstParameterSelector') ...

With your example, it's like

this.parent().prev().find('.results table')

(that's assuming that this.parent().prev() is a jQuery object of course)


The second argument is the the context. For instance, if you wanted to echo the text of the first span element upon clicking any div:

$("div").click(function(){
  alert( $("span:first", this).text() );
});

The this in that example refers to which ever div was clicked. It's our context. This "context" can be a dom-element, document, or jQuery object.

Further reading: http://api.jquery.com/jQuery/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜