2

次のコードを実行すると、同じ要素IDが2回アラートされると予想されますが、代わりに、最初のコードは正しいのに対し、2番目のコードは常にセットの最初の要素の名前を示しています。

$("div.someClass").each(function (index) {
  $(this).click(function () {
    alert($(this).attr("id")); // Here i get the actually clicked element
    $.when($("div.someClass").animate({ }, 0)).then(function () {
      alert($(this).attr("id")); // Here i get the first element in of that class
    });
  });
});

なんでそうなの?それを解決する方法は?要素の名前を関数に渡そうとしましたが、機能しませんでした。

4

3 に答える 3

4

$(this)たとえば、をいくつかの変数に保存しthat、後で使用するanimate

$("div.someClass").each(function (index) {
  $(this).click(function () {
    alert($(this).attr("id")); // Here i get the actually clicked element
    var that = $(this);
    $.when($("div.someClass").animate({ }, 0)).then(function () {           
      alert(that.attr("id")); // Here i get the first element in of that class
      alert($(this).attr("id")); 
    });
  });
});
于 2012-07-27T16:56:03.207 に答える
4

の値はthis、関数呼び出しごとに自動的に変更されます。したがって、複数の関数呼び出しが、コールバックを呼び出す前に特定の値をthis渡し、それを使用.apply()または設定することによって意図的にその値を保持するように共謀しない限り、それは異なります。.call()Javascriptは次のルールに従います。

  • メソッド呼び出しを行うと、の値はthisそのメソッドを持つオブジェクトに設定されます。
  • 通常の関数呼び出しを行うと、thisはグローバルオブジェクトに設定されます(通常window)。
  • fn.apply()またはfn.call()を使用するthisと、最初の引数に基づいて設定されます。

this最も簡単な解決策は、の値をローカル変数に保存してからそれを参照することです。

$("div.someClass").each(function (index) {
  var self = $(this);
  self.click(function () {
    alert(self.attr("id")); // Here i get the actually clicked element
    $.when($("div.someClass").animate({ }, 0)).then(function () {
      alert(self.attr("id")); // Here i get the first element in of that class
    });
  });
});
于 2012-07-27T17:00:19.053 に答える
2

各関数の要素にアクセスする必要があります:http://api.jquery.com/each/

$("div.someClass").each(function (index, element) {
  $(element).click(function () {
    var $this = $(this);
    alert($this.attr("id")); // Here i get the actually clicked element
    $.when($("div.someClass").animate({ }, 0)).then(function () {
      alert($this.attr("id")); // Here i get the first element in of that class
    });
  });
});

また、「this」の意味を理解するのにも役立ちます。https ://developer.mozilla.org/en/JavaScript/Reference/Operators/this jQueryは、「this」が何であるかについての理解を混乱させ、すべてのコンテキストが変化する可能性があります。イベント処理のために行います。

于 2012-07-27T17:01:50.743 に答える