jQuery / 核心 / $(expression, [context] ) 函数
jQuery( expression, context ) 返回: jQuery
This function accepts a string containing a CSS or basic XPath selector which is then used to match a set of elements.
此函数可接受包含CSS或是基本XPath选择器的字符串,以此来匹配一组元素。
The core functionality of jQuery centers around this function. Everything in jQuery is based upon this, or uses this in some way. The most basic use of this function is to pass in an expression (usually consisting of CSS or XPath), which then finds all matching elements.
jQuery的功能性核心都以此函数做为中心。在jQuery中的每样东西都倚赖这个函数,或着在一些方法中使用这个函数。这个函数最基本的使用方法就是给予一条表达式(通常是由CSS或是XPath组成),然后函数会搜寻所有吻合的元素。
By default, if no context is specified, $() looks for DOM elements within the context of the current HTML document. If you do specify a context, such as a DOM element or jQuery object, the expression will be matched against the contents of that context.
默认情况,如果没有关联指定,$() 会寻找当前HTML文档中的DOM元素。如果你指定了关联,例如DOM元素或是jQuery对象,那表达式将会匹配与之相应的内容。
See Traversing/Selectors for the allowed CSS/XPath syntax for expressions.
查看官方对于CSS/XPath表达式上的语法信息
个人实践
看API不亲自动手真弄不懂什么情况,尤其是那个 context 不知道其确切的用途。好了,现在开始举几个例子。本人使用的是jQuery1.1.4,如果有不对的地方应该是版本不同导致。
实验用的HTML代码:
<h1 id=”t1″><span>第一部分</span> 马克思注意<span>哲学<b>原理</b></span></h1>
先尝试没有指定context的情况下指向h1下的所有span元素:
$(”//h1[@id=’t1′]/span”)
$(”h1#t1 span”)
以上两个都是选中h1下所有的span元素,第一个为XPath语法,第二个是CSS语法
下面我们来尝试带有context的情况:
$(”span”,”//h1[@id=’t1′]”)
$(”span”,”h1#t1″)
比较了之后才发现context原来可以看作一个参照点,如果你指定了这个参照点,则表达式会在这个参照点的基础上进行匹配查找。
如果想检查本人有没写错的话可以用$(…).text(),看看是不是把span元素里的文字抓出来了。

Leave a Reply