2013-02-16 50 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 
    }); 
});