1

私は次のコードを持っています:

function Selector()
{
 ...
 this.items = new Array();
 // i load here the items with dom-s
 this.setActiveItem = function(item)
 {
  this.items[item].className = "selector-item-active";
  ...
 }
 var _this = this;
 for (var i=0; i<itemsName.length; i++)
  this.items[i].addEventListener("mouseup",function(){_this.setActiveItem(i)});
}

問題は、リスナーがsetActiveItem関数を呼び出すと、コンソールに次のメッセージが表示されることです。

未定義のプロパティ'className'を設定できません

したがって、リスナーはこの値を渡すことができません。

解決策はありますか?

4

2 に答える 2

1

thisイベント リスナーは、それらが属するオブジェクトのスコープを保持しません。また、クロージャーを使用してアイテム インデックスをコールバックにカプセル化する必要があります。_this代わりに、次のように (定義したように) を使用して変数を参照してみてください。

this.setActiveItem = function(item)
{
    return function (evt) {
        _this.items[item] = _this.items[item] || {};
        _this.items[item].className = "selector-item-active";
        ...
    }
}

...

for (var i=0; i<itemsName.length; i++)
    this.items[i].addEventListener("mouseup", this.setActiveItem(i));
于 2013-03-10T21:09:02.523 に答える
0

itemsName.lengthi の値は、 mouseup イベントが実行されるたびに at と等しくなり ます。匿名関数を使用して i を保持します。

変更されたコード:

.......
 var _this = this;
 for (var i=0; i<itemsName.length; i++){
  (function(j){
           _this.items[j].addEventListener("mouseup",
                        function(){
                              _this.setActiveItem(j);
                        }
                 );
            })(i);// preserve i for each for loop iterations
 }
}
于 2013-03-10T21:10:03.833 に答える