0

I'm trying to load X amount of <li>'s into a <ul> via a for loop in a jquery function, and while I think I've got the syntax about right I'm not getting anything loading. (no problem with loading a single <li>, but none for multiples with the method I've tried)

Initially I attempted to pass a variable into the loop to determine the amount of increments: var peekListAmount = 5;

That didn't work so I went for a bog-standard loop incrementer. That doesn't work either so, after searching here and getting close, I have put together a fiddle to see if someone can point out what I'm doing wrong: http://jsfiddle.net/janowicz/hEjxP/8/

Ultimately I want to use Knockout.js to dynamically input a number to pass to the loop amount variable, but 1st things 1st.

Many thanks in advance.

4

4 に答える 4

3

あなたがするとき:

var peekListItem = $('<li>...</li>');

jQuery オブジェクトにカプセル化されたノードの単一インスタンスを作成しています。<li>

既存のノードを DOM に追加すると、DOM ツリーの現在の場所からノードが削除され、新しい場所に移動されます。

ループの外側ではなく、ループの内側にノードを作成する必要があります。そうしないと、そのノードのコピーではなく、毎回同じノードを再追加するだけです。

実際、そのノードを操作していない場合は、必要な HTMLをまったく.append()ラップせずに呼び出しの中に直接配置できます。$(...)

$(function() {
    var peekList = $('<ul class="peekaboo-list">').appendTo('div.peekaboo-wrap');

    function addLiAnchorNodes(nodeAmount) {
        var html = '<li><a href="#" class="peekaboo-link"></a>' +
                   '<p class="peekaboo-text"></p></li>';

        for (var i = 0; i < nodeAmount; ++i) {
            peekList.append(html);
        }
    }
    addLiAnchorNodes(5);
});

http://jsfiddle.net/alnitak/8xvbY/を参照してください

于 2013-04-29T12:11:16.157 に答える
0

これを試して:

$(function(){
    var peekList = $('<ul class="peekaboo-list"></ul>');


    $(peekList).appendTo('div.peekaboo-wrap'); // This bit works fine

    var addLiAnchorNodes = function (nodeAmount){
        //var nodeAmount = peekListAmount;
        for (var i = 0; i < 10; i++){
            var peekListItem = $('<li><a href="#" class="peekaboo-link"></a><p class="peekaboo-text"></p></li>');
            peekListItem.appendTo(peekList);
        }

    }
    addLiAnchorNodes();
});
于 2013-04-29T12:25:09.990 に答える