`
adamed
  • 浏览: 181385 次
社区版块
存档分类
最新评论

JQuery CookBook翻译连载4

阅读更多

1.4 在特定的上下文 中查找元素

问题

 

你需要使用jQuery 提供的方法从指定的DOM 元素或document 对象中获取一个或多个DOM 元素,并 对其进行相关操作。

 

解决方案

 

当你使用CSS 选择器的时候,你可以向jQuery 方法中传递第2 个参数以指定预查找的DOM 元素的上下文。第2 个参数可以是一个DOM 对象的引用、一个jQuery 对象或者是document 对象。下面的 代码中共有12<input> 元 素。请注意:我如何使用特定的基于<form> 元素的上下文选择<input> 元素。

 Code:

 
<!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">
//searches within all form elements, using a wrapper for context, alerts "8 inputs"
//查询所有的form元素中查找input,打印"8 inputs"  
alert('selected ' + jQuery('input',$('form')).length + ' inputs');
//search with the first form element, using DOM reference as the context, alerts "4 inputs"
//使用DOM对象作为第2参数的方式,在第一个form元素下查找input元素,打印"4 inputs"
alert('selected' + jQuery('input',document.forms[0]).length + ' inputs');
//search within the body element for all input elements using an expression,alerts "12 inputs"
//使用jQuery对象作为第2参数的方式,在body下查询所有的input元素,打印"12 inputs"  
alert('selected' + jQuery('input','body').length + ' inputs');
</script>
</body>
</html>
 

 

讨论

在我们讨论使用document 作为上下文查询对象的时候,仍然有一些需要注意的问题。例如:无法将Ajax 请求返回的XML 文档作为上下文查询其中的对 象。你可以在第16 章找到更多的相关内容的细节。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics