views:

37

answers:

1

I have absolutely no idea why this is happening but the following code seems to be executed a huge amount of times in all browsers.

$('#save_albums').click(function(){
    for(var i = 1; i <= 5; i++){
        html = $('#your_albums ol li').eq(i).html();
        alert(html);
    }
});

Looks fairly innocent to me...

Here's the code in its entirety

$(function(){
    $('#query').keyup(function(){
        var text = encodeURI($(this).val());
        if(text.length > 3){                        
            $('#results').load('search.php?album='+text, function(){

                $('.album').hover(function(){
                    $(this).css('outline', '1px solid black')
                },function(){
                    $(this).css('outline', 'none')
                });

                $('.album').click(function(){
                    $('#fores').remove();
                    $('#yours').show();                                 

                    if($('#your_albums ol li').length <= 4){
                        albumInfo = '<li><div class="album">' + $(this).html() + '</div></li>';

                        if($('#your_albums ol li').length >= 1){
                            $('#your_albums ol li').last().after(albumInfo);
                        }
                        else{
                            $('#your_albums ol').html(albumInfo);
                        }
                    }
                    else{
                        alert('No more than 5 please');
                    }
                });

                $('#clear_albums').click(function(e){
                    e.preventDefault;
                    $('#your_albums ol li').remove();
                });

                $('#save_albums').click(function(){
                    for(var i = 1; i <= 5; i++){
                        html = $('#your_albums ol li').eq(i).html();
                        alert(html);
                    }
                });

            });
        }
        else{
            $('#results').text('Query must be more than 3 characters');
        }
    });
}); 
+3  A: 

Basically what you are doing: Every time KeyUp fires, you load the results and attach an additional .click handler to $('#save_albums'), which is bad. (jQuery can bind multiple functions to an event, so if you call $('something').click(function(){alert('x');}); 3 times, you get 3 alerts)

Depending on your exact usage, you can call $('#save_albums').unbind('click'); to remove all click handlers before you add it:

            // Unbind existing
            $('#save_albums').unbind('click');

            $('#save_albums').click(function(){
                for(var i = 1; i <= 5; i++){
                    html = $('#your_albums ol li').eq(i).html();
                    alert(html);
                }
            });

Alternatively, you can try restructuring the source code to have the click handler only attached once.

Michael Stum