Change() inside each() jQuery

前端 未结 4 2109
抹茶落季
抹茶落季 2020-12-18 06:36

What is the best way to manage this kind of situation :

$(\'.element\').each(function() {

    $sibling = // find a sibling to $this.
    $mainElement = $(         


        
相关标签:
4条回答
  • 2020-12-18 07:09

    Try with this

    $('.element').each(function() {
        $(this).siblings('.sibling').change(function() {
           var mainElement = $(this).siblings('.element');
            // Play here
        });
    });
    
    0 讨论(0)
  • 2020-12-18 07:17

    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)

    0 讨论(0)
  • 2020-12-18 07:28

    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...
        });
    });
    
    0 讨论(0)
  • 2020-12-18 07:31
    $('.element .sibling').each(function( ind, el) {
    
        $parent = $( el ).closest( '.element' );
        $( el ).change(function() {
             $parent.doSomething();
        });
    
    });
    
    0 讨论(0)
提交回复
热议问题