change()里面的每个()jQuery [英] Change() inside each() jQuery
问题描述
$('。element')。每个(功能(){
$ sibling = //找到一个兄弟给$ this
$ mainElement = $(this); //记住$(this)
$ sibling.change (function(){
//当兄弟更改
//使用$ mainElement
//执行某些操作//问题是,$ mainElement不是您认为的元素
// $ mainElement是最后一个发现的元素....
})
});
一个解决方案将是一个表...但是,对于change()到嵌套在每个()...
我的html示例:
< div id =first>
< span class =element>< / span>
< input name =firsttype =text/>
< / div>
< div id =second>
< span class =element>< / span>
< input name =secondtype =text/>
< / div>
在这个例子中, $ sibling = $(this).next('输入');
。
一种方法是使用<一个href =https://stackoverflow.com/a/111200/165154>关闭。这将捕获 $ mainElement
中的变量,可以使用其当前值。
每个(function(){
$ sibling = //找到一个兄弟给$ this $ $ $ $ $ $ $ $ $ $ $ $ mainElement = $(this); //记住$(this)
$ sibling.change(function($ mainElement){
return function(){
// use $ mainElement
}
}($ mainElement))
});
jsfiddle示例 (一定要模糊文本框,编辑后,否则 .change()
将不会触发) / p>
What is the best way to manage this kind of situation :
$('.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....
})
});
One solution would be a table... But then there is no advantage for the change() to be nested in the each()...
My html example :
<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>
In this exemple, $sibling = $(this).next('input');
for instance.
One way to do it, is to use a closure. This will capture the variable in $mainElement
, so to speak, using its current value.
$('.element').each(function() {
$sibling = // find a sibling to $this.
$mainElement = $(this); // memorize $(this)
$sibling.change(function($mainElement) {
return function() {
// use $mainElement
}
}($mainElement))
});
jsfiddle example (be sure to blur the textfield, after editing, otherwise .change()
won't fire)
这篇关于change()里面的每个()jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!