【问题标题】:Snap.svg — remove an object when one of the elements was clickedSnap.svg — 单击其中一个元素时删除一个对象
【发布时间】:2015-03-21 18:23:15
【问题描述】:

我有一个对象,它在一组中绑定了 3 个元素,当单击绿色矩形时,我需要删除该对象(或至少它的图形表示 - 组)。 a.click() 有效,但 c.click() 无效,我想知道原因:

var s = Snap(500, 500);

function myObj() {

    this.g = s.group();

    this.drawIt = function() {

    var a = s.rect(0, 0, 50, 50, 0, 0).attr({'fill':'#E82941'}),
        b = s.rect(20, 20, 50, 50, 0, 0).attr({'fill':'#FF6E00'}),
        c = s.rect(40, 40, 50, 50, 0, 0).attr({'fill':'#00C049'});

        this.g.append(a, b, c);

        a.click(function(e){this.attr({'fill':'#000'});});
        c.click(this.killIt);
    }

    this.killIt = function() {
        this.g.remove();    
    }

}

var obj = new myObj();

obj.drawIt();

Snap.svg 0.3.0。

已解决:http://codepen.io/GeMir/pen/KwbBqV

【问题讨论】:

    标签: javascript svg snap.svg


    【解决方案1】:

    这是关闭的问题,c.click 处理程序中的this 不代表myObj

    在构造函数myObj 中声明一个变量var that=this;,如下所示

    function myObj() {
    
      var that = this;
    
      this.g = s.group();
    
      this.drawIt = function() {
        var a = s.rect(0, 0, 50, 50, 0, 0).attr({'fill':'#E82941'}),
            b = s.rect(20, 20, 50, 50, 0, 0).attr({'fill':'#FF6E00'}),
            c = s.rect(40, 40, 50, 50, 0, 0).attr({'fill':'#00C049'});
    
            this.g.append(a, b, c);
    
            a.click(function(e){this.attr({'fill':'#000'});});
            c.click(function(e){that.killIt()});
      }
    
      this.killIt = function() {
                this.g.remove();    
      }
    
    }
    
    var obj = new myObj();
    
    obj.drawIt();
    

    如果在另一个函数中声明一个函数,this 变量将与父函数的变量不同。在这种情况下,它将指向c对象,在a.click的情况下,由于this指向a,它起作用了。

    【讨论】:

    • 谢谢! that.killIt() 仅删除“a”而不是完整组。有没有办法删除包括“a”、“b”和“c”形状的组?
    • 因为,g 中只有 a,而不是 this.append(a,b,c) 尝试 this.g.append(a); this.g.append(b);this.g.append(c); 。它奏效了。
    • 谢谢!我以前从未使用过带有多个参数的附加。
    • 出于兴趣,将this.killIt 替换为() => {this.killIt()} 是否也有效?
    猜你喜欢
    • 2018-06-24
    • 2018-10-05
    • 1970-01-01
    • 2021-08-18
    • 2016-05-12
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多