使用Javascript的ID无法正常工作

时间:2012-11-22 15:55:56

标签: javascript raphael

在Raphaeljs中,它编写了这行代码:(仅显示相关部分)

......
    sets.id = index;
    grid.hex[poly].click(
      function(e)
    {   
        var id=this.id
.....

它正确设置sets []的id,但是“this”的id是集合内部路径的id,即被点击的id。我必须拥有套装的ID。我怎么能做到这一点?

修改: 我希望“this”成为集合,而不是被点击的路径。

2 个答案:

答案 0 :(得分:1)

将功能绑定到sets

......
    sets.id = index;
    grid.hex[poly].click($.proxy(function(e){
         var id = this.id;
    }, sets);
.....

或者如果你没有使用jQuery。

//https://gist.github.com/978329
if(!Function.prototype.bind) {
   Function.prototype.bind = function(to){
        // Make an array of our arguments, starting from second argument
    var partial = Array.prototype.splice.call(arguments, 1),
        // We'll need the original function.
        fn  = this;
    var bound = function (){
        // Join the already applied arguments to the now called ones (after converting to an array again).
        var args = partial.concat(Array.prototype.splice.call(arguments, 0));
        // If not being called as a constructor
        if (!(this instanceof bound)){
            // return the result of the function called bound to target and partially applied.
            return fn.apply(to, args);
        }
        // If being called as a constructor, apply the function bound to self.
        fn.apply(this, args);
    }
    // Attach the prototype of the function to our newly created function.
    bound.prototype = fn.prototype;
    return bound;

}

grid.hex[poly].click(function(e){
         var id = this.id;
    }.bind(sets));

答案 1 :(得分:0)

你试过吗?:

var id = this.parentElement.id

<强>更新

来自http://raphaeljs.com/

  

Raphaël['ræfeɪəl]使用SVG W3C推荐标准和VML作为基础   用于创建图形。 这意味着您创建的每个图形对象   也是一个DOM对象,因此您可以附加JavaScript事件处理程序或   稍后修改它们。

假设sets是一个图形对象(并且因为它包含路径,我认为它是),那么this应该有一个parentElement属性来访问。

如果它不起作用,您也可以尝试访问它:

var id = sets.id;

由于关闭而应该有效。

相关问题