jQuery与javascript对照学习(获取父子前后元素)

<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>
posted @ 2009-10-06 15:10  大气象  阅读(1803)  评论(0编辑  收藏  举报
http://www.tianqiweiqi.com