首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

JQuery CookBook通译连载4

2012-11-23 
JQuery CookBook翻译连载41.4 在特定的上下文中查找元素问题?你需要使用jQuery提供的方法从指定的DOM元素

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章找到更多的相关内容的细节。

热点排行