Contents
- UNIX
- Windows
- サーバ
- プログラミング言語
- データベース
- プロトコル
- サービス
- オープンソース
- 規格・技術
- アプリケーション
- PC
- DEVICE
- その他(未分類)
お問合せ:
メールフォーム
jQuery には、ループ内で処理を飛ばしたり、抜けたりする命令である continue と break が用意されていない。
が、 return 命令 を使うことで同等のことが可能になる。
ループの先頭に戻る(処理を飛ばす)
$('li').each(function (idx) { if (idx === 2) return; alert(idx); });
ループを抜ける
$('li').each(function (idx) { if (idx === 2) return false; alert(idx); });
果物
<script type="text/javascript">
String.prototype.trim = function() {
return this.replace(/^[\s ]+|[\s ]+$/g, '');
}
</script>
<script type="text/javascript" src="/path/to/js/jquery.js"></script>
<script type="text/javascript">
$(function(){
/**
* continue
*/
$('#continue').click(function(){
$('#fruit li').each(function (idx) {
var text = $(this).text().trim(); // trim() = IE対策
if (text === 'バナナ') return;
alert((idx+1) + ': ' + text);
});
});
/**
* break
*/
$('#break').click(function(){
$('#fruit li').each(function (idx) {
var text = $(this).text().trim(); // trim() = IE対策
if (text === 'バナナ') return false;
alert((idx+1) + ': ' + text);
});
});
});
</script>
<b>果物</b>
<ol id="fruit">
<li>スイカ</li>
<li>メロン</li>
<li>バナナ</li>
<li>オレンジ</li>
<li>グレープフルーツ</li>
</ol>
<div><input id="continue" type="button" value="continue のデモ"> ←「バナナ」を飛ばします。</div>
<div><input id="break" type="button" value="break のデモ"> ←「バナナ」の直前でループを抜けます。</div>