Change() inside each() jQuery

雨燕双飞 提交于 2019-11-29 08:16:38
Decent Dabbler

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)

Try with this

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

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

});

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:

$('.element').each(function() {
    $(this).siblings('.sibling').change(function() {
        var mainElement = $(this).siblings('.element');
        // Do whatever you want here...
    });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!