2012-11-22 30 views
0

在Raphaeljs不起作用,它寫了這行代碼:(僅相關部分所示)ID使用JavaScript需要

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

它設定集的ID []正常,但ID 「this」是集合內部路徑的ID,即被點擊的路徑。我必須擁有套的ID。我怎麼能做到這一點?

編輯: 我希望「this」是集合,而不是被點擊的路徑。

+0

由於關閉,處理程序裏面沒有'index'嗎? – David

+0

這是一個函數裏面,集合在一個數組裏面,並且有很多不相關的東西我沒有包含。我不能像原樣使用索引。 –

+0

'var id = sets.id'?這是你在找什麼? – bfavaretto

回答

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)); 
+0

我很困惑,爲什麼寫這行? :var setID = id;? –

+0

使當前索引在您的點擊處理程序中可用。 –

+0

給了我相同的,點擊路徑後它給我的路徑,而不是設置爲「這個」 –

0

你有沒有試過?:

var id = this.parentElement.id 

UPDATE:

http://raphaeljs.com/

拉斐爾['ræfeɪəl]使用SVG W3C推薦標準和VML作爲基礎 用於創建圖形。 這意味着您創建的每個圖形對象 也是一個DOM對象,因此您可以附加JavaScript事件處理程序或 以後修改它們。

假設sets是圖形對象(和,因爲它包含的路徑,我假設它是),那麼this應該有一個parentElement屬性來訪問。

如果它不工作,你也可以嘗試訪問它:

var id = sets.id; 

這應該是因爲封閉的工作。

+0

不parentElement只適用於DOM?設置不是DOM的一部分 –

+0

不行,parentElement是undefined –