2012-10-22 2 views
1

"볼"이라는 하나의 개체를 만듭니다. 문서로드 후, 스크립트는 개체의 12 인스턴스를 생성하고알림 기능이 각각의 색인을 표시하지 않는 이유

<ul></ul> 

내 목적은 클릭 볼, 그것은 볼 인덱스를 보여줄 때이다에 많은 요소 리를 삽입합니다. 예 : 아니오 3 볼을 클릭하십시오. 3 공을 클릭하십시오. 3 볼을 클릭하면 항상 12가 표시됩니다.

죄송합니다.

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

사용자가 클릭 한 요소를 캡처해야합니다. 즉, 출력 한 볼 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)}); 
} 

}};

내가 주석 처리 한 행과 볼리바르의 HTML에 첨부 된 클릭 이벤트 함수를 주목하십시오.

이벤트 및 이벤트 전파에 대해 자세히 알아보십시오. here

+1

코드에서 _this global을 만들었습니다. 그러므로 포스터의 원래 문제입니다. – epascarello

+0

그건 거짓입니다. 쉼표를 추가해도이 문제는 해결되지 않습니다. – instinctious

+0

이것은 구현하기위한 또 다른 좋은 방법입니다. 감사. – user1765418

관련 문제