Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

event handling - Change() inside 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....
    })
});

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...