本文介绍jQuery函数中第二个参数用于指定DOM元素搜索范围的使用方法。详细解析了三种上下文类型:DOM reference、jQuery wrapper和document,并通过包含表单和输入元素的完整HTML示例代码,演示了不同参数类型下的选择器行为与结果。
jQuery第二个参数指定搜索范围
jQuery构造函数的context参数用于限定DOM元素的查找范围。
上下文参数类型
该参数支持多种类型:
DOM引用
jQuery包装集
文档对象
代码示例与验证
代码演示
具体实现如下:
<!DOCTYPE html>
<html>
<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="jquery-1.11.1.js"></script>
<script type="text/javascript">
// 基于jQuery包装集查找所有form内的input,
// 弹出提示包含8个input元素
alert("selected" + $('input', $('form')).length + ' inputs');
// 基于第一个form DOM元素查找,
// 弹出提示包含4个input元素
alert("selected" + $('input', document.forms[0]).length + ' inputs');
// 基于body元素查找所有input,
// 弹出提示包含12个input元素
alert("selected" + $('input', 'body').length + ' inputs');
</script>
</body>
</html> 归纳
不同参数类型对应的调用方式见下表。
| 类型 | 用法 |
|---|---|
| jQuery wrapper | $('input', $('form')).length |
| DOM reference | $('input', document.forms[0]).length |
| document | $('input', 'body').length |