JQuery.each 遍歷一個集合的時候,有時候我們不需要完全遍歷,在找出需要的數據的時候,想跳出 JQuery.each 這個時候,問題出現了。
常規思維方式:
<form id="form1" runat="server"> <div> <p>1</p> <p>2</p> <p>3</p> <p>4</p> <p>5</p> <p>6</p> <p>7</p> <p>8</p> </div> </form> <script type="text/javascript"> $(function () { $('p').each(function () { if ($(this).text() == "2") { $(this).text('0'); /* 這里的 return 語句,和 continue 語句一樣,跳出了本次循環,沒有達到預期的目的。 */ return; } else { alert($(this).text()); } }); }); </script>
哈哈,常規思維方式寫出的代碼,return 語句,盡然做起了 containue 語句的事情,新手這里可能就迷糊了,一時半會反應不過來。
修改后的代碼:
<form id="form1" runat="server"> <div> <p>1</p> <p>2</p> <p>3</p> <p>4</p> <p>5</p> <p>6</p> <p>7</p> <p>8</p> </div> </form> <script type="text/javascript"> $(function () { try { $('p').each(function () { if ($(this).text() == "2") { $(this).text('0'); /* 這里的 return 語句,和 continue 語句一樣,跳出了本次循環,沒有達到預期的目的。 */ /* return; */ throw 'someError'; } else { alert($(this).text()); } }); } catch (err) { if (err == 'someError') { return; } } }); </script>
結尾語:這里利用了 try...catch 語句,來跳出 JQuery.each 循環,可以看成是一個小技巧,或者娛樂一下吧,實際項目中還是要根據情況而定。