2012-10-22 26 views
1

我創建了一個名爲「Ball」的對象。 文檔加載後,腳本將創建對象的實例12,並插入如此多的元素裏,以爲什麼alert函數不顯示每個的索引

<ul></ul> 

我的目的是,當點擊球,它顯示球的指數。 爲〔實施例:單擊否3球,這表明3 但是當我點擊每個球,它總是顯示12

對不起,我不能上傳快照html文件,因爲我在這裏是新來的傢伙。

function Ball(idx, parent, libra) { 
    this.idx = idx; 
    this.parent = parent; 
    this.libra = libra; 
    this.init(); 
} 

Ball.r = 30; 

Ball.prototype = { 
    init: function() { 
     var _html = $("<li><div class='ball'><span>" + this.idx + "</span></div></li>"), 
     pos 
     _this = this; 
     this.parent.append(_html); 
     this.html = _html.find(".ball"); 
     this.html.css({ 
      height: Ball.r * 2 + "px", 
      width: Ball.r * 2 + "px", 
      lineHeight: Ball.r * 2 + "px" 
     }); 
     pos = this.html.position() 
     this.html.css({ 
      left: pos.left + "px", 
      top: pos.top + "px", 
      position: "absolute" 
     }); 
     this.html.mousedown(function() {alert(_this.idx)}); 
    } 
}; 


$("document").ready(function() { 
    var parent = $("#balls ul"), 
    libra = 1; 
    for (var i = 1; i < 13; i++) { 
     new Ball(i, parent, libra) 
    } 
}); 

回答

0

您錯過了一個逗號,因此_this是全球性的。

var _html = $("<li><div class='ball'><span>" + this.idx + "</span></div></li>"), 
    pos <--- missing comma here 
    _this = this; 

由於它是全球性的,所以您正在獲取創建的最後一個球的值。

解決方案:

添加缺少的逗號。

+0

謝謝。已經解決了。 – user1765418

0

您需要捕獲用戶點擊的元素。這意味着您需要監聽您輸出的Ball html上的點擊事件。你的球對象應該是這樣的:

Ball.prototype = { 
init: function() { 
    var _html = $("<li><div class='ball'><span>" + this.idx + "</span></div></li>"), 
    pos; 
    _this = this; 
    this.parent.append(_html); 
    this.html = _html.find(".ball"); 
    this.html.css({ 
     height: Ball.r * 2 + "px", 
     width: Ball.r * 2 + "px", 
     lineHeight: Ball.r * 2 + "px" 
    }); 
    pos = this.html.position() 
    this.html.css({ 
     left: pos.left + "px", 
     top: pos.top + "px", 
     position: "absolute" 
    }); 

    $(_html).on("click", function(e) { 
     alert(e.currentTarget.textContent); 
    }); 

    //this.html.mousedown(function() {alert(_this.idx)}); 
} 

};

注意我註釋的行和我附加到您的Ball li的html的單擊事件函數。

閱讀更多關於事件和事件傳播here

+1

您在代碼中創建了_this全局。因此,海報的原始問題。 – epascarello

+0

這是錯誤的。添加一個逗號並不能解決這個問題。 – instinctious

+0

這是實施的另一個好方法。謝謝。 – user1765418

相關問題