Nested jQuery.each() - continue/break

后端 未结 11 492
天涯浪人
天涯浪人 2020-12-05 03:52

Consider the following code:

    var sentences = [
        \'Lorem ipsum dolor sit amet, consectetur adipiscing elit.\',
        \'Vivamus aliquet nisl quis          


        
11条回答
  •  失恋的感觉
    2020-12-05 04:50

    I've used a "breakout" pattern for this:

    $(sentences).each(function() {
        var breakout;
        var s = this;
        alert(s);
        $(words).each(function(i) {
            if (s.indexOf(this) > -1)
            {
                alert('found ' + this);
                return breakout = false;
            }
        });
        return breakout;
    });
    

    This works nicely to any nesting depth. breakout is a simple flag. It will stay undefined unless and until you set it to false (as I do in my return statement as illustrated above). All you have to do is:

    1. declare it in your outermost closure: var breakout;
    2. add it to your return false statement(s): return breakout = false
    3. return breakout in your outer closure(s).

    Not too inelegant, right? ...works for me anyway.

提交回复
热议问题