2012-03-13 108 views
-1

我不明白什么是功能推的使用,它有什么帮助。 1 - 为什么我需要行代码?为什么我需要推送功能?

circles.push(newCircle); 

2 - 我将此代码复制到html文件,代码没有运行,我应该错过这里的东西吗? THX

<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

看起来像你缺少你标签的命名空间? – DdD 2012-03-13 22:23:11

+0

实际上它的工作原理。 http://jsfiddle.net/eU32w/ – DdD 2012-03-13 22:25:32

+1

@DimitriAdamou小提琴正在工作,因为左上角的任何东西都包含在' ...'中。 – 2012-03-13 22:29:29

回答

2
  1. .push是一个阵列的方法,这增加了Circle实例到集合(数组)circles

    circles数组用作块代码片段circles[i].update()末尾的参考集。

  2. 在遇到<body>之前,您正在使用document.body参考。因此,document.bodyundefined,并且您的代码会引发错误。
    要么将​​<script>块放在<body>之内,要么通过脚本标记上的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

谢谢,你有更多的示例simulate.push(newCircle); – user1255490 2012-03-13 22:40:29

0

Ahhaha,这是我的代码。我想知道为什么它看起来很熟悉。你把它放在错误的地方。在我为您制作的原始小提琴中,它响应于窗口加载事件而运行。

你既可以自己做,也可以把脚本标签放在身体而不是头部。

等待加载事件,用这种替代线路document.body.appendChild(svgElement);

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

thx你可以有更多的这样的推送功能这个问题我不是用svg填写100%的理解吗? – user1255490 2012-03-13 22:51:46

+0

“推送功能”只是将项目添加到数组中的一种方式。它与svg无关。我只是保存所有的圈子,所以我可以循环播放动画。 – david 2012-03-13 22:55:34

+0

非常感谢我的代码 – user1255490 2012-03-13 23:00:04

相关问题