jQuery与javascript对照学习 获取父子前后元素 实现代码

  作者:bea

<html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>jQuery与javascript对照学习(获取父子前后元素)</title> <style type="text/css"> .c1{background-color:green;padding:20px;} .c2{background-color:red;padding:20px;} .c1


<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>jQuery与javascript对照学习(获取父子前后元素)</title>
<style type="text/css">
.c1{background-color:green;padding:20px;}
.c2{background-color:red;padding:20px;}
.c1 div{background-color:gray;}
</style>
<script type="text/javascript" src="style/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
function fNext(obj){//许多时候需要元素之间没有间隙才能取到
//alert(obj.nextSibling.id);
alert(jQuery(obj).next().attr("id"));//传递this,通过$(obj)转化为jQuery对象
}
function fPrev(obj){
//alert(obj.previousSibling.id);
alert(jQuery(obj).prev().attr("id"));
}
function fParent(obj){
//alert(obj.parentNode.className);
//alert(jQuery(obj).parent().attr("class"));
jQuery(obj).parent().removeClass("c1").addClass("c2")
alert(jQuery(obj).parent().attr("className"));//取得className,当成属性来取
}
function fChild(obj){
//var childs = obj.childNodes;
var childs = jQuery(obj).children();
for(i=0;i<childs.length;i++){
alert(childs[i].id);
}
//jQuery的each遍历
}
</script>
</head>
<body>
<div class="c1" onclick="fChild(this);">
<div id="first" onclick="fNext(this);">first</div>
<div id="second" onclick="fPrev(this);">second</div>
<div id="third" onclick="fParent(this);">parent</div>
</div>
</body>
</html>




[Ctrl+A 全选 注:
如需引入外部Js需刷新才能执行]



有用  |  无用

猜你喜欢