0

次の仮説コードを見てください。

// create some list we work with
$('body').html('<ul class="collection-list"></ul>');

// some array with string data
var collection = ['foo', 'bar', 'foobar'];

// here we store our jquery objects
var doms = [];

// for each item in the collection array we create a li
$.each(collection, function(index, value) {
    // imagine that the jquery part would return a reference/object which we push into our doms array
    doms.push($('ul.collection-list').append('<li class="item">' + value + '</li>'));
});

// we could now do different logic through our cached object
doms[2].val('new value');
doms[1].remove();

この例は論理的な意味をなさない可能性がありますが、代替案を示さないでください! 提示されたテクニックを使いたいだけです。例はほんの一例です!

4

1 に答える 1

1

ul個々の s ではなく、要素全体をループに格納するliということです。

$.each(collection, function(index, value) {
    doms.push($('<li class="item">' + value + '</li>'));
    $('ul.collection-list').append(doms[index]);
});

doms[2].html('new 3rd li value');
于 2012-07-24T15:58:04.043 に答える