您的位置:首页 > Web前端 > JQuery

DOM 和 jQuery对象相互转换 以及for-in和$.each遍历方法

2016-07-04 11:59 971 查看
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="../reset/reset.css">
<script type="text/javascript" src="../jquery/jquery.min.js"></script>
</head>
<body>
<!-- 	DOM对象,即是我们用传统的方法(javascript)获得的对象,jQuery对象即是用jQuery类库的选择器获得的对象;
复制代码 代码如下:

var domObj = document.getElementById("id"); //DOM对象
var $obj = $("#id"); //jQuery对象; -->
<div id="c"></div>
<h2>锄禾日当午</h2>
<h2>汗滴禾下土</h2>
<h2>谁知盘中餐</h2>
<h2>粒粒皆辛苦</h2>
<script>
var c = document.getElementById('c');
var cc = $("#c");
document.write('***************************')
var domc = $('#c')[0];
var domc = $('#c').get(0);
//上面两种方法都行  将jquery对象转换为dom对象
var $jqc = $(c)//将dom对象转换为jquery对象
console.log('-----------------------------------------')
//遍历
var h = $('h2');
$('h2').each(function(index,value){
console.log(index);
console.log(value)
});
$.each(h,function(index,value){
console.log(index);
console.log(value);
});
var hh = {'姓名' : '张三',年龄 : 22,sex : 'nan'};
console.log(hh.sex)
console.log(hh['姓名']+hh['年龄']);
$.each(hh,function(index,value){
console.log(index);
console.log(value);
})
for(index in hh){
console.log(index);
console.log(hh[index]);
}
var hhh = [{'姓名':'Tom'},{'age':14},123,'Happy NewYear!'];
$.each(hhh,function(index,value){
console.log(index);
console.log(value)
})
for(index in hhh){
console.log(index);
console.log(hhh[index])
}
console.log('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');
for( i in h){
console.log(i)
}
var DH = document.getElementsByTagName('h2');
for(var i=0;i<DH.length;i++){
console.log(DH[i].innerHTML)
}
var $dh = $(DH);
console.log(DH);
console.log($dh)
$.each($dh,function(index,value){
console.log(index);
console.log(value)
})
//个人总结  如果是自己var 的对象 或者数组  用for-in  或者$.each或者$().each都可以遍历
//如果是通过DOM或者jquery获取的对象 要用$.each或者$().each遍历
//DOM对象也可以用for循环遍历
</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: