2012-03-13 2 views
-1

나는 함수 푸시의 사용법과 그것이 어떻게 도움이되는지 이해할 수 없다. 1 - 회선 코드가 필요한 이유가 무엇입니까?왜 푸시 기능이 필요합니까?

circles.push(newCircle); 

2 -이 코드를 html 파일에 복사하고 코드가 실행되고 있지 않습니다. 들으

<html> 
<head> 
<title>Your title here</title> 

<script type = "text/javascript" language = "Javascript"> 
<!-- Hide from older browsers; 
var svgns = 'http://www.w3.org/2000/svg'; 
var svgElement = document.createElementNS(svgns, 'svg'); 
document.body.appendChild(svgElement); 

var Circle = function(x,y,size){ 
    this.element = document.createElementNS(svgns, 'circle'); 
    this.x = x; 
    this.y = y; 
    this.size = size; 

    this.dx = 10*(Math.random()-0.5); 
    this.dy = 10*(Math.random()-0.5); 

    this.element.setAttribute('cx', this.x+'px'); 
    this.element.setAttribute('cy', this.y+'px'); 
    this.element.setAttribute('r', this.size+'px'); 
    this.element.setAttribute('stroke', 'black'); 
    this.element.setAttribute('stroke-width', '2px'); 
    this.element.setAttribute('fill', 'red'); 

    svgElement.appendChild(this.element);  
}; 

Circle.prototype.update = function(){ 
    this.x += this.dx; 
    this.y += this.dy; 
    this.element.setAttribute('cx', this.x+'px'); 
    this.element.setAttribute('cy', this.y+'px'); 
}; 


var circles = []; 
for (var i = 0; i< 10; i++) { 
    var newCircle = new Circle(100,100,10); 
    circles.push(newCircle);  
} 

window.setInterval(function(){ 
    for (var i = 0; i< circles.length; i++) { 
     circles[i].update(); 
    }  
}, 30); 




// end hide --> 
</script> 
</head> 
<body> 
<!-- Insert HTML here --> 

</body> 
</html> 
+0

보이는 :

이 함께 라인 document.body.appendChild(svgElement);를 교체로드 이벤트를 기다립니다? – DdD

+0

실제로 작동합니다. http://jsfiddle.net/eU32w/ – DdD

+1

@DimitriAdamou 상단 블록의 내용이 ' ...'에 포함되어 있기 때문에 바이올린이 작동하고 있습니다. –

답변

2
  1. .push 컬렉션 (배열)에 circlesCircle 인스턴스 추가 배열 방법이다.

    circles 배열은 코드 조각 circles[i].update()의 끝에있는 블록의 참조 세트로 사용됩니다.

  2. <body>이 발생하기 전에 document.body 참조를 사용하고 있습니다. 결과적으로 document.bodyundefined이고 코드에서 오류가 발생합니다.
    <body> 내에 <script> 블록을 넣거나 스크립트 태그의 window.onload=function(){ ... code here... } 또는 defer 속성을 통해 스크립트를 연기하십시오.

1
  1. push 방법은 어레이의 단부에 하나 개 이상의 요소를 추가한다. 자세한 내용은 MDN documentation을 참조하십시오. 무엇을 작동하지 않습니다

    var sports = ["soccer", "baseball"];

    sports.push("football", "swimming");

    // Now, sports = ["soccer", "baseball", "football", "swimming"]

  2. : 여기 그것이 작동하는 방법의 예?

+0

감사합니다. simular에서 circles.push (newCircle)까지 더 많은 샘플을 가지고 있습니까? – user1255490

0

아하하, 내 코드입니다. 나는 그것이 왜 그렇게 익숙해 보였는지 궁금해했다. 당신은 그것을 잘못된 장소에 넣었습니다. 원래 필자는 윈도우로드 이벤트에 응답하여 실행했습니다.

직접 처리하거나 스크립트 태그를 머리가 아닌 본문에 넣을 수 있습니다. 당신이 당신의 태그 네임 스페이스 누락처럼

window.addEventListener('load', function(){ 
    document.body.appendChild(svgElement); 
}); 
+0

thx 당신은 푸시 함수로 이것처럼 더 많은 examle을 가질 수 있습니까? svg와 100 % 이해를 채우지 않습니까? – user1255490

+0

'푸시 기능'은 배열에 항목을 추가하는 단순한 방법입니다. 그것은 svg와는 아무런 관련이 없습니다. 애니메이션을 위해 반복 할 수 있도록 모든 서클을 저장했습니다. – david

+0

고맙습니다. 귀하의 코드를 좋아합니다. – user1255490