2011-05-06 4 views
3

以下のように私はいくつかのjQueryのコードを記述します。私はにconsole.log結果は同じになりたいが、それは間違っている作品

$('.button').each(function(){ 
    $(this).click(function(){ 
     console.log($(this)); 
     do_sth(); 
    }); 
}); 

var do_sth = function(){ 
    console.log($(this)); 
} 

...最初はのHTMLElementを指し、 2番目はDOMWindowを参照しています... do_sth関数をすべてHTMLElementを参照するように書き直すにはどうすればよいですか?おかげさまで

+1

あなたが行った解決策を受け入れることを忘れないでください。 – alex

+0

ここで問題となるのは、このキーワードはあなたがやろうとしていることをしないということです。それは文脈に完全に依存します。 http://justin.harmonize.fm/index.php/2009/09/an-introduction-to-javascripts-this/ –

答えて

9

あなたが行うことができます...

do_sth.call(this); 

また、あなたはjQueryのproxy()メソッドを使用することができます。

$.proxy(do_sth, this)(); 

jsFiddle

+0

これで動作します。ありがとうございました。 – shawjia

1

ここで方法は次のとおりです。ちょうど$(this).click(function() { $(this).do_sth(); });

2.にあなたの操作を行い、他のFNで

$.fn.do_sth = function() { console.log(this); }; 

:あなたはそれ原型機能することができます

$('.button').click(function() { 
     do_sth.call(this); 
    }); 
}); 
4

1.使用可能.call

do_sth.call(this); 

3.あなたは、要素パラメータを期待し、それを変更することができます。

function do_sth(el) { console.log(el) } 
+0

prototypal関数は素晴らしいソリューションです。ありがとうございます。 – shawjia

+0

+1の代替方法の良いリスト。 – alex

0

は、あなたが呼び出す関数にパラメータを渡します。ここ

$('.button').each(function(){ 
    $(this).click(function(){ 
     console.log($(this)); 
     do_sth(this); 
    }); 
}); 

var do_sth = function(button){ 
    console.log(button); 
} 

はフィドルです:http://jsfiddle.net/JfwNJ/

+0

数秒遅くなります。 go figure =) – matchew

0

その後、パラメータとして(この)要素$を取るためにdo_sth関数を記述:

$('.button').each(function(){ 
    var $that = $(this); 
    $(this).click(function(){ 
     console.log($that); 
     do_sth($that); 
    }); 
}); 

var do_sth = function($el) { 
    console.log($el) 
} 

はその後、これを行います