在循环中移除动态图像

时间:2014-02-26 22:05:50

标签: javascript image kineticjs

我在循环中创建了几个动态图像并将它们保存在一个数组中。现在我想为每个图像创建一个onclick-function,将其删除。 代码如下:

var arr = [];

for (var i = 0; i < 30; i++) {
var osix = new Kinetic.Image({
image: images.Osi1, 
x: Math.floor(Math.random()*900+0),
y: Math.floor(Math.random()*600+0)
});
arr.push(osix); //works fine
}

for (image in arr) {
arr[image].on('click', function() {
        writeMessage(score_counter);  //also works fine
    arr[image].remove();  //no error, but the removal is not appearing 
    layer.draw();
    score_counter += 1;
    if (score_counter >= 20) {finishing_fun();}
    });
}

然而,如果我这样做,它可以工作:

var osi1 = new Kinetic.Image({
image: images.Osi1, 
x: Math.floor(Math.random()*900+0),
y: Math.floor(Math.random()*600+0)
});

osi1.on('click', function() {
writeMessage('50!!');
osi1.remove();
layer.draw();
    score_counter += 1;
if (score_counter >= 20) {finishing_fun();};
}

1 个答案:

答案 0 :(得分:2)

当您的点击功能被调用时,索引(图像)不再可用。

因此,在您的点击功能中使用this来引用图像对象本身。

重构代码和演示:http://jsfiddle.net/m1erickson/LLbFM/

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Prototype</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    <script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v4.7.2.min.js"></script>
<style>
body{padding:20px;}
#container{
  border:solid 1px #ccc;
  margin-top: 10px;
  width:350px;
  height:350px;
}
</style>        
<script>
$(function(){

    var stage = new Kinetic.Stage({
        container: 'container',
        width: 350,
        height: 350
    });
    var layer = new Kinetic.Layer();
    stage.add(layer);

    var img=new Image();img.onload=start;img.src="house16x16.png";

    var arr = [];
    var score_counter=0;

    function start(){

        for (var i = 0; i < 3; i++) {

            var osix = new Kinetic.Image({
                image: img, 
                x: i*20,
                y: 30
            });
            layer.add(osix);
            arr.push(osix); //works fine

        }
        layer.draw();

        for(i in arr){
            arr[i].on('click', function(){
                this.remove();
                layer.draw();
                score_counter += 1;
                if (score_counter >= 20) {finishing_fun();}
            });
        }
    }

}); // end $(function(){});

</script>       
</head>
<body>
    <h4>Click image to remove it</h4>
    <div id="container"></div>
</body>
</html>