我想使用JQuery使用以下技術來獲取子元素的ID。但是,似乎代碼無法在循環中執行。爲什麼發生這種情況,我怎樣才能得到每個孩子的ID?爲什麼它不顯示我的子元素的ID?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JQuery</title>
<script type="text/javascript" src="jquery.js"> </script>
<style type="text/css">
#parent{width:50%;margin:auto;border:#000 thick groove;overflow:hidden;}
#child1{float:left;width:50px;height:50px;background-color:#00F;}
#child2{float:left;width:50px;height:50px;background-color:red;margin-left:30px}
#child3{float:left;width:50px;height:50px;background-color:#00F;}
#child4{float:left;width:50px;height:50px;background-color:red;margin-left:30px}
#child5{float:left;width:50px;height:50px;background-color:#00F;}
#child6{float:left;width:50px;height:50px;background-color:red;margin-left:30px}
#child7{float:left;width:50px;height:50px;background-color:#00F;}
#child8{float:left;width:50px;height:50px;background-color:red;margin-left:30px}
</style>
</head>
<body>
<div id="parent">
<div id="child1"></div>
<div id="child2"></div>
<div id="child3"></div>
<div id="child4"></div>
<div id="child5"></div>
<div id="child6"></div>
<div id="child7"></div>
<div id="child8"></div>
</div>
<script type="text/javascript">
var child = $('#parent').children().length;
var chil;
for (i = 0;i<child;i++){
chil = $('#parent').children()[i].attr('id');
alert(chil);
}
</script>
</body>
</html>
你也可以看看jQuery的each()方法。它將使您無需完全編寫自己的循環代碼。 – JohnFx