每个()jQuery中的Change()

管理这种情况的最佳方法是什么:

$('.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.... }) }); 

一个解决方案是一个表……但是,将()嵌套在each()中没有任何优势……

我的html示例:

 

在这个例子中, $sibling = $(this).next('input'); 例如。

一种方法是使用封闭 。 这将捕获 $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()将不会触发)

试试这个

 $('.element').each(function() { $(this).siblings('.sibling').change(function() { var mainElement = $(this).siblings('.element'); // Play here }); }); 
 $('.element .sibling').each(function( ind, el) { $parent = $( el ).closest( '.element' ); $( el ).change(function() { $parent.doSomething(); }); }); 

我要说的最简单的赌注是在兄弟姐妹身上使用.each,然后为兄弟姐妹找到相对的“.element”。 当然取决于您的代码。 否则,这样的事情可能会起作用,即使由于.each感觉有点多余:

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