2010-04-08 56 views

回答

11

**更正:添加更多詳情。使用一個標誌,允許從父函數返回**

function foo() { 
    var doreturn = false; 
    jQuery(whatever).each(function() { 
    if(youwanttoreturn){ 
     doreturn=1; 
     return false; 
    } 
    }); 
    if(doreturn)return; 
} 

http://api.jquery.com/each/ 「我們可以通過返回false從回調函數中停止循環。」

+1

他想從「foo」回來! – Pointy 2010-04-08 17:18:48

+1

使用變量+1。它比使用try/catch稍快。看看我這個jsPerf:http://jsperf.com/returning-a-parent-function-from-inside-a-child – 2012-08-02 20:03:26

4

該函數可以返回false

編輯哦哈哈, 「從富」 被滾出右側:)

要做到這一點,你可以使用try/catch語句

function foo() { 
    try { 
    jQuery('whatever').each(function() { 
     if (noMoreFoo()) throw "go"; 
    }); 
    } 
    catch (flag) { 
    if (flag === "go") return; 
    throw flag; 
    } 
} 
+1

它稍快使用一個變量來檢查是否必須比使用try/catch語句返回。看看我這個jsPerf:http://jsperf.com/returning-a-parent-function-from-inside-a-child – 2012-08-02 20:03:46

1

不是。這將貧民窟做你想做的(我認爲):

function foo() { 
    var bar=null; 
    $(whatever).each(function() { 
     bar="bar"; 
     return false; 
    }); 
    return bar; 
} 
var fooResults = foo(); 
+0

+1爲「貧民窟做」 – iamwhitebox 2014-01-22 00:17:14

0
function foo() { 
    $result = false; 
    jQuery(whatever).each(function() { 
      $result = true; 
    }); 
    // We will reach this point after the loop is over. 
    return $result; 
} 
+0

?? ??我不認爲這會做任何事情;就像jQuery一樣,它就像'return'一樣沒有價值。 – Pointy 2010-04-08 17:17:37

+0

@Pointy謝謝,更正。 – 2010-04-08 17:20:30

相關問題