2011-06-18 45 views
2

我想使用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> 
+0

你也可以看看jQuery的each()方法。它將使您無需完全編寫自己的循環代碼。 – JohnFx

回答

4

children()[i]在返回的DOM元素不是一個jQuery對象,所以你不能在它調用attr。如果您將其更改爲children().eq(i).attr它應該可以工作。

5

你可以在jQuery中以更簡單的方式做到這一點。這段代碼可以替代整個塊。

$('#parent').children().each(function() { alert(this.id); }) 
+1

你的意思是'$('#parent')。children()。each'。 –

+0

是。謝謝。固定。 – JohnFx

+1

+1用於*不*對'.attr()'進行不必要的調用。 – user113716

1
$("#parent").children().each(function(index, element) 
{ 
    alert($(this).attr("id")); 
}); 

這應該工作。

1
$('#parent').children().each(function(index, value) { 
    alert($(this).attr('id')); 
}); 
+0

@ben。哦,我們發佈了同樣的東西:) –

+0

是的,和@JohnFx幾乎一樣:) – Ben

相關問題