2011-06-23 23 views
0

(它的很多剝離出來)由於代碼的函數

// A data set 
$.DataArea = function() { 

    // Default options 
    $.extend(this, { 
     'class': "DataSet", 
     'bars': new Array(), 
     'container': null, 
     'containerId': null, 
     'gridsize': 20, 
     'width': 400, 
     'height': 400, 
     'currentSelectedBar': 0 
    }); 

    // Add a bar to this object 
    this.addBar = function(startDate, endDate, label, styleID) { 

     // When the bar is clicked 
     $('#' + barID).click(function() { 

      alert($(this).currentSelectedBar); 
      if (this.currentSelectedBar != undefined) 
       $('#' + this.currentSelectedBar).fadeIn("slow"); 

      this.currentSelectedBar = barID; 
       $('#' + barID).fadeTo("slow", 0.5); 

     }); 
    } 

當我alert($(this).currentSelectedBar);它永遠是爲未定義,這不是正確的值設置裏面引用此。任何想法,爲什麼這可能是?

這個想法是,當你點擊一個酒吧,淡出它,當你點擊另一個最後一個酒吧淡出淡入。

+1

我覺得你不只是這一個問題了。由於@Robert在他的評論中正確地指出了我的(現在已刪除的)答案,「this」指向你綁定事件處理程序的DOM元素。 –

回答

1

假設你對DataArea實例調用addBar,你的代碼應該是:

// Add a bar to this object 
this.addBar = function(startDate, endDate, label, styleID) { 
    var self = this; 
    // When the bar is clicked 
    $('#' + barID).click(function() { 

     alert(self.currentSelectedBar); 
     if (self.currentSelectedBar != undefined) 
      $('#' + self.currentSelectedBar).fadeIn("slow"); 

     self.currentSelectedBar = this.id; 
     $(this).fadeTo("slow", 0.5); 
    }); 
} 

裏面的click處理器,this將參考DOM元素'#' + barID。但是這些屬性被分配給其他元素,而不是DOM元素。

+0

非常感謝! –

1

回調函數中的this指的是上升事件的元素:在這種情況下爲$('#' + barID)。 我想你想訪問你擴展的this。在這種情況下,你應該寫這樣的事情:

this.addBar = function(startDate, endDate, label, styleID) { 
    var self = this 

    // When the bar is clicked 
    $('#' + barID).click(function() { 

     alert($(self).currentSelectedBar); 
     if (self.currentSelectedBar != undefined) 
      $('#' + self.currentSelectedBar).fadeIn("slow"); 

     self.currentSelectedBar = barID; 
     $(this).fadeTo("slow", 0.5); 

    }); 
} 
1
var that = this; 
    $('#' + barID).click(function() { 

     alert(that.currentSelectedBar); 
     if (that.currentSelectedBar != undefined) 
      $('#' + this.currentSelectedBar).fadeIn("slow"); 

     that.currentSelectedBar = barID; 
      $('#' + barID).fadeTo("slow", 0.5); 

    }); 

緩存點擊函數外的值this。在點擊功能中,上下文this是被點擊的DOM節點。

1

看起來你對jQuery的行爲有問題。

$('#' + barID).click(function() {重新映射this的定義,但之前嘗試向其添加屬性將不起作用,因爲this的定義已被覆蓋。

正如recmashak你可以把原來this到一個變量,然後使用它時,你做你的警告中提及

+0

jQuery與它無關。這是基本的Javascript範圍規則。 –

+0

我不認爲我說的一定是錯的。這是jQuery開發人員在事件處理程序內重新映射「this」的有意識的決定。原型不會這樣做(您改爲調用'event.element()')。如果沒有重新映射'this',它會引用'this.addBar'對象,這是JavaScript範圍規則(並且與原來擴展的'this'不同) – nzifnab