jQuery 中的 each() 中的 Change()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14910100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:04:38  来源:igfitidea点击:

Change() inside each() jQuery

jqueryevent-handling

提问by Lyth

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()...

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

My html example :

我的 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>

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

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

回答by Decent Dabbler

One way to do it, is to use a closure. This will capturethe variable in $mainElement, so to speak, using its current value.

一种方法是使用闭包。可以说,这将使用其当前值捕获 中的变量$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(be sure to blur the textfield, after editing, otherwise .change()won't fire)

jsfiddle 示例(编辑后一定要模糊文本,否则.change()不会触发)

回答by Gautam3164

Try with this

试试这个

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

回答by Roko C. Buljan

$('.element .sibling').each(function( ind, el) {

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

});

回答by Somersault

I'd say the easiest bet for you is to use an .each on the siblings, and then finding the relative ".element" for the sibling. Depends on your code of course. Otherwise, something like this might work, even though it feels a bit redundant due to the .each:

我想说对你来说最简单的方法是在兄弟姐妹上使用 .each,然后为兄弟姐妹找到相对的“.element”。当然取决于你的代码。否则,这样的事情可能会奏效,尽管由于 .each 感觉有点多余:

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