html5中文学习网

您的位置: 首页 > 网站及特效实例 > javascript特效 » 正文

jQuery函数的第二个参数获取指定上下文中的DOM元素_jquery_

[ ] 已经帮助:人解决问题
jQuery函数的第二个参数可以指定DOM元素的搜索范围。

第二个参数可分为以下类型

DOM reference
jQuery wrapper
document

代码示例
复制代码 代码如下:

<!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">
// search within all form elements, using a wrapper for context,
// alerts "8 inputs"
alert("selected" + $('input', $('form')).length + ' inputs');

// search with the first form element, using DOM reference as the context,
// alerts "4 inputs"
alert("selected" + $('input', document.forms[0]).length + ' inputs');

// search within the body element for all input elements using an expression,
// alerts "12 inputs"
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
(责任编辑:)
推荐书籍
推荐资讯
关于HTML5先行者 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助