jquery prev 函数实例

prev() 函数被用来匹配元素集的前一个兄弟元素,仅仅只有前一个兄弟元素被选择,其子元素将被忽略。

 

prev() 函数可以允许通过选择器来过滤,例如 prev(‘div’) 被用来选择匹配元素的前一个元素是兄弟元素的div元素。

具体实例代码:

<html>
	<head>
		<title>
			prev() example
		</title>
		<style type="text/css">
			div,p{
				width:110px;
				height:40px;
				margin:2px 8px 2px 8px;
				float : left;
				border:1px blue solid;
					
				}
			
			</style>
			<script type="text/javascript" src="../jquery-1.11.1.min.js">
				</script>
	</head>
	<body>
		<h1>jquery prev() example</h1>
		<div>
			  this is div 1
			  <div>div 1 child</div>
		</div>
		<p>this is paragraph 1</p>
    <div>
    	this is div 2
    	<div>div 2 child</div>
    	</div>
    	<div id="start"> this is div 3
<div>div 3 child</div>
    	</div>
<br/><br/><br/>
<br/><br/>
<button id="prevButton1">prev()</button>
<button id="prevButton2">prev("div")</button>
<button id="prevButton3">prev("p")</button>
<button id="reset">Reset</button>
<script type="text/javascript">
	var $currElement=$("#start");
	$currElement.css("background","red");
	$("#prevButton1").click(function(){
		if(!$currElement.prev().length){
			alert("no element found");
			return false;
			}
		$currElement=$currElement.prev();
		$("div,p").css("background","");
		$currElement.css("background","red");
		});
	
	$("#prevButton2").click(function(){
		if(!$currElement.prev("div").length){
			alert("no element found");
			return false;
			}
		$currElement=$currElement.prev("div")
		$("div,p").css("background","");
		$currElement.css("background","red")
		
		
		});
		$("#prevButton3").click(function(){
			if(!$currElement.prev('p').length){
				
				alert("no element found");
				return false;
				
				
				}
			
			$currElement=$currElement.prev('p');
			$("div,p").css("background","");
			$currElement.css("background","red");
			
			});
		  $("#reset").click(function () {
	  location.reload();
    });
	</script>
	</body>
</html>


效果:


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值