/ /別の関数内で$(this)参照を使用するにはどうすればよいですか? -javascript、jquery、jquery-selectors、これ

他の関数の中で$(this)参照を使うにはどうすればいいですか? - javascript、jquery、jquery-selector、this

このようなケースがあります-

$("<first-selector>").each(function(){
$(this).click(function(){
$("<second-selector>").click(function(){
/* Here I want to use the top $(this) reference to do some business.
I don"t want to use like var thisObj = $(this) and refer it inside
the click function*/
});
});
});

使い方 $(this) 別のオブジェクト内の参照?

回答:

回答№1は4

つかいます $ .proxy

$("div").each(function(){
$(this).click(function(){
$("p").click($.proxy(function(){
console.log($(this)); // returns <div>
/* Here I want to use the top $(this) reference to do some business.
I don"t want to use like var thisObj = $(this) and refer it inside
the click function*/
}, this));
});
});

デモ: http://jsfiddle.net/TRw4X/


回答№2の場合は0

だからあなたは最初から$(this)を使いたい2番目の関数内で機能し、それを$(this)として参照しますか? jQueryはthis-contextを保持しているため、これは不可能です。次のようなもので実行する必要があります。

$("<first-selector>").each(function()
{
var first = $(this);

first.click(function()
{
$("<second-selector>").click(function()
{
var second = $(this);
// do something with first and second.
});
});
});

回答№3の場合は0

jQueryイベントでオブジェクトの参照を渡すことができます。

$("<first-selector>").each(function(){
$(this).click($(this),function(){
$("<second-selector>").click(function(e){
var $elem = e.data.
/* Here I want to use the top $(this) reference to do some business.
I don"t want to use like var thisObj = $(this) and refer it inside
the click function*/
});
});
});

回答№4の場合は0

質問を「解決」する唯一の方法は、jQueryを使用しないことです。

それでも、jQueryで質問にタグを付けます。

ここで正確に何をしたいのですか?なぜ簡単な(そしてクロージャーを使用する一般的なjavascriptのイディオム)があなたによって却下されたのですか?


回答№5の場合は0

これは最良の解決策ではありませんが(なぜなら他のソリューションが示唆するように変数を介して参照する必要があります)... second-selectorが最初のセレクタの子である場合、常にparent()メソッドを使用できます。

$("<first-selector>").each(function(){
$(this).click(function(){
$("<second-selector>").click(function(){
/*$(this) is now referencing <second-selector> and by adding parent() it will go up the elements until it find the requested selector*/
$(this).parents("<first-selector>").doSomething();
});
});
});

答え№6の場合は0

この場合、DOMですべての最初のセレクターを準備しますクリックイベントハンドラーとバインドされています。最初のセレクターをクリックすると、2番目のセレクターがクリックイベントにバインドされます。最初のセレクタを表す$(this)を使用するには、コードを次のように記述する必要があります。

$("<first-selector>").each(function(){
$(this).click(function(){
var oldthis = $(this);
$("<second-selector>").click(function(){
alert(oldthis.val());
});
});

});

first-selectorタグがsecond-selectorタグと同じでないことを確認してください。 フォームでこれを試してください

jQuery(document).ready(function(){
jQuery("input[type=text]").each(function(){
jQuery(this).click(function(){
var oldthis = jQuery(this);
jQuery("input.hello").click(function(){
alert(oldthis.val());
});
});
});
});

最初にテキスト入力フィールドをクリックします。 Helloクラスのボタンがクリックされると、入力TEXTフィールドの値を警告します。