2

私が次のものを持っていると仮定しましょう...

jQuery('#a').click(function(){
   myFunction();
});
function myFunction(){
  var me = jQuery(this);// this one gets the "window" object instead of "#a" element
}

パラメータとして送信できないmyFuncton間に、イベントを開始したターゲット要素を取得するにはどうすればよいですか。これは、戻ってサイト全体を再チェックし、すべての関数呼び出し引数を変更する必要があるためです...this

4

3 に答える 3

4

したがって、次のことができます。

$('#a').click(myFunction); // then this in myFunction will be the '#a' element.

更新

コールバックで myFunction 以外のことを行う必要がある場合は、指定されたthis 値で関数を実行.call()または実行することができます。.apply()

$('#a').click(function() {
    otherLogic();
    myFunction.call(this);
});
于 2012-10-12T15:51:27.343 に答える
1

これを試して

jQuery('#a').click(function(){
   myFunction(this);
});

function myFunction(elem){
  var me = jQuery(elem);
}

クリックイベントから渡したときに、elem で関数を呼び出した現在のオブジェクトを取得します。

于 2012-10-12T15:54:57.950 に答える
0
jQuery('#a').click(function(){
   myFunction(this);
});
function myFunction(sender){
  if (sender !=undefined)
   {
      var me = jQuery(sender);// and do other stuff
      //.....
   }
   //do your old stuff -- me will be logically out of scope
}
//this will not result in an error, sender will be undefined
// the code will be compatible backwards
myfunction();
于 2012-10-12T16:09:51.043 に答える