开发者

Help understanding jQuery selector example

开发者 https://www.devze.com 2023-03-06 00:50 出处:网络
The following code was taking from the timersjQuery plugin demo.I don\'t understand what is happening in the selector in line 2.It seems it is selecting the p element, but then what is the second argu

The following code was taking from the timers jQuery plugin demo. I don't understand what is happening in the selector in line 2. It seems it is selecting the p element, but then what is the second argument after the comma - demos - there for?

jQuery:

var demos = $("div.wrapper div.demos");             
$(".uncontrolled-interval p", demos).everyTime(1000,function(i) {
                    $(this).html(i);
                });

HTML:

<div class="wrapper"> 
    <div class="demos">         
        <div class="uncontrolled-interval"> 
            <p>I am transient... *sigh*</p> 
        </div>      
    </div> 
</div>
开发者_StackOverflow中文版

Thanks


It specifies the context of the search. Basically a filter.

http://api.jquery.com/jQuery#expressioncontext

So in this example it searches the demos element for .uncontrolled-interval p. If you have this markup, it would still only select the one in demos.

<div class="wrapper">          
    <div class="uncontrolled-interval"> 
        <p>I am transient... *sigh*</p> //Will not select
    </div>     
    <div class="demos">         
        <div class="uncontrolled-interval"> 
            <p>I am transient... *sigh*</p> //Will select
        </div>      
    </div> 
</div>


When selecting elements with jQuery using the jQuery function (or its alias $), you can provide a context as well as a selector as described here.

What that says is: select every element that matches the provided CSS selector within the given context, with context meaning the region of the DOM that you have already selected.

Put another way, it says: use the context as the root of the DOM tree being searched, as opposed to the document root.


In addition to others answer, context works like .find():

Internally, selector context is implemented with the .find() method, so $('span', this) is equivalent to $(this).find('span').

Personnaly, I prefer write demos.find(".uncontrolled-interval p") to $(".uncontrolled-interval p", demos)

0

精彩评论

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