/ each()jQuery内の/ Change() - jquery、イベント処理

各()内のChange()jQuery - jquery、イベント処理

このような状況を管理するための最善の方法は何ですか。

$(".element").each(function() {

$sibling = // find a sibling to $this.
$mainElement = $(this); // memorize $(this)
$sibling.change(function() {
// when sibling changes
// do something using $mainElement
// problem is, $mainElement is not the element you think
// $mainElement is the last .element found....
})
});

1つの解決策はテーブルです…しかし、それではchange()がeach()の中にネストされることには利点がありません...

私のhtmlの例:

<div id="first">
<span class="element"></span>
<input name="first" type="text" />
</div>
<div id="second">
<span class="element"></span>
<input name="second" type="text" />
</div>

この例では、 $sibling = $(this).next("input"); 例えば。

回答:

回答№1は4

その1つの方法は、 閉鎖。この意志 キャプチャー の変数 $mainElementつまり、現在の値を使用しています。

$(".element").each(function() {

$sibling = // find a sibling to $this.
$mainElement = $(this); // memorize $(this)
$sibling.change(function($mainElement) {
return function() {
// use $mainElement
}
}($mainElement))
});

jsfiddleの例 (編集後は必ずテキストフィールドをぼかしてください。 .change() (t火に勝った)


回答№2の場合は1

これを試してみてください

$(".element").each(function() {
$(this).siblings(".sibling").change(function() {
var mainElement = $(this).siblings(".element");
// Play here
});
});

回答№3の場合は1
$(".element .sibling").each(function( ind, el) {

$parent = $( el ).closest( ".element" );
$( el ).change(function() {
$parent.doSomething();
});

});

回答№4の場合は0

私はあなたのための最も簡単な賭けを使用することだと思います。兄弟のそれぞれで、それから兄弟のための相対的な ".element"を見つけます。もちろんあなたのコードに依存します。そうでなければ、たとえそれが.eachのために少し冗長に感じられるとしても、このような何かがうまくいくかもしれません:

$(".element").each(function() {
$(this).siblings(".sibling").change(function() {
var mainElement = $(this).siblings(".element");
// Do whatever you want here...
});
});