开发者

jquery while loop fadeIn each <li> as it gets appended

开发者 https://www.devze.com 2023-02-07 09:05 出处:网络
I\'m trying to fiddle around with this concept and I can\'t seem to get the logic to work and stick. I was wanting a user to enter a digit number and press the add link and when they do that it will

I'm trying to fiddle around with this concept and I can't seem to get the logic to work and stick.

I was wanting a user to enter a digit number and press the add link and when they do that it will add the number they entered as number of contacts and append each new contact to an <li> element, then fade them in one at a time. If the user where to enter another number in the text field for it to then append that new number to the end of the li with an incremented number.

For instance:

[_3_] [Add]
============
Contact 1
Contact 2
Contact 3

Then if they decide to add 2 more contacts:

[_2_] [Add]
============
Contact 1
Contact 2
Contact 3
Contact 4
Contact 5

this is my code: the ID of the UL is new-prospect-add-contacts

//-- Add more contacts

var counter = $("#new-prospect-add-contacts").size();

    $("#e").live("click", function(){


        var e = $("#new-prospect-additional-contact").val();
        while(counter < e)
        {
            $("#new-prospect-add-contacts").append("<li>").append("<span>Contact " + ++counter + "</span>").fadeIn(2000);
        }
        return false;
    });

Behaviors:

I am able to add the number of Contacts based on user input, but they will flash into the <UL> and not apply the .fadeIn()

If a user adds more contacts It appends it t开发者_如何学Co the bottom but starts the count all over again from 2....


your callback scope is destroyed after each 'click', so your counter will not persist.

you could move the counter declaration outside the callback in your script, and it will persist.


See working demo of the following code here.

Instead of using a counter, I used $("#new-prospect-add-contacts").find('li').length being dynamically updated as the list grows to count how many to add, based on how many were already in the list when we start plus the amount to add.

var $npac = $("#new-prospect-add-contacts"),
    addVal = parseInt($("#new-prospect-additional-contact").val(), 10) + $npac.find('li').length;

while ($npac.find('li').length < addVal) {
    // CODE
}

Since we don't cache the length, the while loop will break when we append enough li to the list. Inside the while we append the li items as hidden...

    var nLi = $('<li><span>Contact ' +
                parseInt($npac.find('li').length + 1, 10) + 
                '</span></li>').css('display', 'none');
    $npac.append(nLi);

...so that afterwards we can iterate through them with .each() and use the index to delay when they fadeIn():

$npac.find('li:hidden').each(function(i, obj) {
    $(obj).delay((i+1)*150).fadeIn(600);
});

See demo.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号