2013-03-09 2 views
0

그래서 동일한 ID가 'div'인 div가 여러 개 있습니다. 나는이 모든 요소들을 반복하여 각각 무작위로 높이기를 원합니다. 여기 내가 시도한 것입니다 :동일한 ID의 여러 div를 다른 높이로 변경하십시오.

<script type="text/javascript"> 
     for(var i = 0; i < 47; i++) { 
      var rand = 200; 
      document.getElementsById('stick')[i].style.height= rand+'px'; 
     } 
    </script> 

이 코드는 슬프게도 작동하지 않습니다. 내가 놓친 게 있니?

감사합니다.

답변

4

가 두 개 이상의 요소에 동일한 ID를 추가해서는 안 될 것입니다. 클래스 이름을 사용하십시오. document.getElemetsById은 정의 된 함수가 아니며 하나의 요소를 반환해야하는 document.getElementById ("s"제외) 만 있습니다.

HTML :

<div class="stick"> </div> 
    <div class="stick"> </div> 

JS :

<script type="text/javascript"> 
    var divs = document.getElementsByClassName('stick'); 
    for(var i = 0; i < divs.length; i++) { 
     var rand = 200 * Math.random(); 
     divs[i].style.height= rand+'px'; 
    } 
</script> 

이 수도 작동합니다.

<script type="text/javascript"> 
    $('.stick').each(function(){   //iterates all elements having stick class 
     $(this).height(200 * Math.random());  //inside the callback the 'this' is the current html element. etc ... 
    }); 
</script> 

jQuery를 홈페이지 : http://jquery.com/

빨리 당신의 웹 사이트에 포함 바로 CDN의 URL에서 jQuery를 가져,이 선이 jQuery를에 간단한 코드되기 때문에하지만, 자바 스크립트 코딩의 jQuery 프레임 워크를 사용하는 것이 좋습니다 , 머리 안쪽 :

<head> 
     ... 
     <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script> 
    </head> 
0

ID는 문서 내에서 완전히 고유해야합니다. ID를 고유 한 값으로 변경하면 개별적으로 참조 할 수 있습니다. 요소 컬렉션에 대해 작업하려면 class 태그를 사용하여 요소를 연결하십시오. CSS Classes에서 읽을 수있는 내용은 this documentation입니다. 이렇게하면 HTML 및 CSS의 클래스 목적을 이해하는 데 도움이됩니다.

당신의 문제

getElementsByID()이 작동하지 않습니다. getElementByID()은 올바른 구문입니다.

그래서

document.getElementsById('stick')[i].style.height= rand+'px'; 

document.getElementById('stick')[i].style.height= rand+'px'; 
0

id이 여러 개인 요소는 가질 수 없습니다. id의 고유 한이어야합니다. class을 사용하고 클래스 이름을 사용하여 요소를 검색해야합니다. jquery를 사용하여 다음을 지원할 수 있습니다. var elements = $('.stick')

관련 문제