views:

37

answers:

2

Am I doing something wrong? Or is there a better way to do this?

This is the code I have:

//Create as many li's as needed
for(var t = 1; t <= pageLimit; t++) {
        if (t <= 9) {
            $('ul.thumb-list').append('<li><p>PAGE ' + t + '</p><img id="' + t + '" src="../jpeg/thumbnails/0' + t + '.jpg" /></li>'); 
        } else if (t >=10) {
            $('ul.thumb-list').append('<li><p>PAGE ' + t + '</p><img id="' + t + '" src="../jpeg/thumbnails/' + t + '.jpg" /></li>'); 
        }



        // for each li that gets click, produce a click function that will get its id               
        $('ul.thumb-list li').each(function() {
                $(this).click(function() {
                    var currId = $(this).attr('id');

                    //Testing to see if it is right
                    alert('currId is: ' + currId);

                    if(currId <=9){
                        $('#page' + currId).empty();
                        $('#page' + currId).append('<img class="touch" src="../jpeg/pages/0' + currId + '.jpg"/>');
                    } else if (currId >=10) {
                        $('#page' + currId).empty();
                        $('#page' + currId).append('<img class="touch" src="../jpeg/pages/' + currId + '.jpg"/>');
                    }


                    jQT.goTo($('#page' + currId), 'slide');
                });
            });

}

My main question is did I set up the click and each function properly.. or should it be another way?

Also my alert won't show the currId. Is there any reason why?

+4  A: 

First off you don't need the each. You can simply do:

$('ul.thumb-list li').click(function(){
    // function body
});

Second of all, there is no ID on the list items that you are adding to the list. It's the images that have their IDs set.

I think you want code that works something like:

$('ul.thumb-list li').click(function(){
    var currId = $('img', this).attr('id');
    alert('currId is: ' + currId);

    // rest of your code
});
Justin Niessner
She's selecting every `li` but would need to go to the children `img` to get the `id`, assuming I'm reading her HTML correctly.
Jeff Rupert
Ahh thank you! I knew there was something wrong.. Im new to jquery, thanks for the help
cat
A: 

If there are multiple tags that you would like to be able to click, you should use

$('tag').live('click', function(){

});

It's more efficient, but if you only have 1 tag that needs to be able to click (say an ID) then .click() should be just fine.

MoDFoX