原文:
http://www.lifelaf.com/blog/?p=196
本文翻译自jQuery Cookbook (O’Reilly 2009) 1.4 Selecting DOM Elements Within a Specified Context
需求
在某个DOM元素内或者某个文档中,选择单个或者多个DOM对象。
解决方案
当给jQuery函数传CSS表达式的时候,我们可以多传一个参数给它,这个第二个参数指代的是jQuery根据CSS表达式搜索DOM对象的范围(上下文背景),这个参数可以是一个DOM对象,可以是封装后的jQuery对象,也可以是一个文档对象。在下述示例中有12个<input>元素,通过用<form>元素来定义搜索范围,我们可以选择特定的<input>元素:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <form> <input name="" type="checkbox" /> <input name="" type="radio" /> <input name="" type="text" /> <input name="" type="button" /> </form> <form> <input name="" type="checkbox" /> <input name="" type="radio" /> <input name="" type="text" /> <input name="" type="button" /> </form> <input name="" type="checkbox" /> <input name="" type="radio" /> <input name="" type="text" /> <input name="" type="button" /> <script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/JavaScript"> //在所有form元素中搜索,使用封装后的form对象作为上下文,弹出"8 inputs" alert('selected ' + jQuery('input',$('form')).length + ' inputs'); //在第一个form元素中搜索,使用DOM对象作为上下文,弹出"4 inputs" alert('selected' + jQuery('input',document.forms[0]).length + ' inputs'); //在body元素中搜索所有的input元素,弹出"12 inputs" alert('selected' + jQuery('input','body').length + ' inputs'); </script> </body> </html>
讨论
正如上面所提到的,可以选择文档作为搜索的范围。比如,可以在XHR请求(Ajax)所获取的XML文档中进行搜索。