2013-02-16 11 views
1

什么是管理这种情况的最好办法:内的每个变化()()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.... 
    }) 
}); 

一个解决方案是一个表......但后来就没有优势的变化()被嵌套在各()...

我的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');例如。

+0

您是否尝试过的:var $ =兄弟//找到兄弟姐妹到$这。 var $ mainElement = $(this); – luckystars 2013-02-16 12:11:31

+0

发表html,很抱歉等待。 – Lyth 2013-02-16 15:31:26

回答

4

一种方式做到这一点,是使用closure。这将捕获变量在$mainElement,可以这么说,使用其当前值。

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

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

jsfiddle example(一定要模糊的文本框,编辑后,否则.change()不会闪光)

+0

完美,正是我期待的:) – Lyth 2013-02-16 15:43:45

0

我想说的最简单的赌注是对兄弟姐妹使用.each,然后找到兄弟姐妹的相对“.element”。取决于你的代码当然。否则,这样的事情可能会奏效,虽然感觉有点多余因。每个:

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

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

}); 
+0

这似乎是另一个适当的解决方案。你宁愿这样做而不是封闭,为什么? – Lyth 2013-02-16 15:56:14

1

尝试用这种

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