[jquery] append をもっと活用する

jQueryを使っているとわりと良くある状況:例えば、$.getで持ってきた情報に基づいて div#container にJavaScriptでp要素を追加する方法についてもっと考えてみます。

リストのそれぞれについてp要素を作って追加したい場合、ループ中でひとつひとつちまちまと append や appendTo で追記していく方法もありますが、配列演算と組み合わせられるようにするため、一気にやる方法について考えてみました。

appendのドキュメント を読むと、複数の引数をとることができるようなので、これを活用します。

// 1. よくあるコード
$('#container').append($('<p />').text('foo'));

// 2. jQuery(html, props) を使う
$('#container').append($('<p />', {text: 'foo'}));

// 3. append(content, content, ...) appendは複数個の引数をとることができます
$('#container').append(
    $('<p />', {text: 'foo'}),
    $('<p />', {text: 'bar'})
);

// 3a. 関数オブジェクトのメソッドapply(context, [arg1, arg2, ...]) を使って、配列でappendします。
// $.fn.append = $.prototype.appendです。
$.fn.append.apply($('#container'), [
    $('<p />', {text: 'foo'}),
    $('<p />', {text: 'bar'})
]);

// 3b. 配列を作る部分を $.map(list, fn)に置き換えます
$.fn.append.apply($('#container'), $.map(['foo', 'bar'], function (item) {
    return $('<p />', {text: item});
}));

// 4. もしくは、appendにelementArrayを与える方法
$('#container').append($.map(['foo', 'bar'], function (item) {
    return $('<p />', {text: item})[0];
}));

この方法を使えば、良くあるデータ構造(ハッシュのリスト) からの table の動的生成も以下のように簡単に書くことができます。

var $table = $('<table />'),
    list = [
        {
            name: '佐藤一郎',
            address: '東京都新宿区',
            tel: '0312341234'
        },
        {
            name: '山田太郎',
            address: '大阪府大阪市北区',
            tel: '0612341234'
        }
    ];

$table.append($('<tr />').append(
    $.map(['名前', '住所', '電話番号'], function (item) {
        return $('<th />', {text: item})[0];
    })
));

$table.append($.map(list, function (r) {
    return $('<tr />').append($.map([r.name, r.address, r.tel], function (item) {
        return $('<td />', {text: item})[0];
    }))[0];
}));

$('#container').append($table);

/*
<table>
<tr><th>名前</th> <th>住所</th> <th>電話番号</th></tr>
<tr><td>佐藤一郎</td> <td>東京都新宿区</td> <td>0312341234</td></tr>
<tr><td>山田太郎</td> <td>大阪府大阪市北区</td> <td>0612341234</td></tr>
</table>
*/

出力例
名前 住所 電話番号
佐藤一郎 東京都新宿区 0312341234
山田太郎 大阪府大阪市北区 0612341234
前回の jQuery の記事 [jquery] jQuery(html, props)が便利 もぜひ併せてご参照ください。

コメント

このブログの人気の投稿

[linux] ping は通るのに No route to host と言われる

Chrome でダウンロードしたファイル名の一部がハイフンになる

[windows] Windows 回復環境 (WinRE) を修理する