在each() jQuery 中更改() [英] Change() inside each() jQuery

查看:12
本文介绍了在each() jQuery 中更改()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

One solution would be a table... But then there is no advantage for the change() to be nested in the each()...

我的 html 示例:

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>

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

In this exemple, $sibling = $(this).next('input'); for instance.

推荐答案

一种方法是使用 闭包.这将捕获 $mainElement 中的变量,可以说,使用它的当前值.

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 示例(一定要模糊文本字段,编辑后,否则 .change() 不会触发)

这篇关于在each() jQuery 中更改()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆