jquery API .find()

.find()

描述: 通过一个选择器,jQuery对象,或元素过滤,得到当前匹配的元素集合中每个元素的后代。


.find(selector)

selector

类型: Selector

一个用于匹配元素的选择器字符串。


.find(jQuery object)

jQuery object

类型: Object

现有匹配当前元素集合的jQuery对象。


.find(element)

类型: Element

一个匹配当前元素集合的元素。

如果一个jQuery对象表示一个DOM元素的集合, .find()方法允许我们能够通过查找DOM树中的这些元素的后代元素,匹配的元素将构造一个新的jQuery对象。.find().children()方法是相似的,但后者只是再DOM树中向下遍历一个层级(愚人码头注:就是只查找子元素,而不是后代元素)。

.find()方法还可以接受一个选择器表达式,该选择器表达式可以是任何可传给$()函数的选择器表达式。如果紧随兄弟匹配选择器,它将被保留在新构建的jQuery对象中;否则,它被排除在外。

例子:

Example: 开始搜索段落所有后代的span元素,和$("p span")一样
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<script src="jquery-1.10.2.js" ></script>

</head>

<body>
<p><span>Hello</span>, how are you?</p>
<p>Me? I'm <span>good</span>.</p>
<script>
 	$("p").find("span").css('color','red');
</script>
</body>
</html>

效果图:


Example: 一个选择使用的所有span标签jQuery集合。只有spans在P标签更改为红色,而另一些是蓝色。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<script src="jquery-1.10.2.js" ></script>
<style>
	span{color:blue;}
</style>
</head>

<body>
<p><span>Hello</span>, how are you?</p>
<p>Me? I'm <span>good</span>.</p>
<div>Did you <span>eat</span> yet?</div>
<script>
	var $spans = $("span");
	$("p").find($spans).css("color","red");
</script>

</body>
</html>
效果图:

Example: 为每个单词添加 span 标签,并为 span 标签添加 hover 事件,并且将含有 t 的单词变为斜体。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<script src="jquery-1.10.2.js" ></script>

  <style>
  p { font-size:20px; width:200px; cursor:default; 
      color:blue; font-weight:bold; margin:0 10px; }
  .hilite { background:yellow; }
  </style>
</head>

<body>

<p>
  When the day is short
  find that which matters to you
  or stop believing
</p>
<script>
	var newText = $("p").text().split(" ").join("</span> <span>");
	newText = "<span>" + newText + "</span>";
	
	$("p").html( newText )
		.find('span')
		.hover(function(){
			$(this).addClass("hilite");
		},
		function(){
			$(this).removeClass("hilite");
		})
	.end()
		.find(":contains('t')")
		.css({"font-style":"italic", "font-weight":"bolder"});
</script>
</body>
</html>
效果图:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值