2

With this code, I'm trying to dynamically bind a click event to an element and reference an incremented variable:

<script type="text/javascript" src="/js/jquery-1.5.1.min.js"></script>
<script language="javascript">
$(document).ready(function() {
function preprocessPage(id){    
        $('.nextPage').click(function(){
            showPage(++id);
        });
    }

function showPage(id){
    console.log('showing: '+id);
        preprocessPage(id);
    }   


showPage(1);//init
});
<div class="nextPage">show next page</div>

When the page loads, it seems to work as expected. And the first click seems to work. Then things get screwy. It seems to run through the code multiple times (increasing by a factor of 2) Here's what you'd see in the firebug console if you click the div 4 times (the first log line occurs after the init load):

showing: 1

showing: 2

showing: 3

showing: 3

showing: 4

showing: 4

showing: 4

showing: 4

showing: 5

showing: 5

showing: 5

showing: 5

showing: 5

showing: 5

showing: 5

showing: 5

Please help! What's going on? Thanks in advance....

1 Answer 1

3

Each click calls show page that adds a new onclick handler to the elements matched with the selector .nextPage.

Sometimes it's good to execute the code in your head or in paper to understand what's going on. I've emphasized the events where things get out of hand.

  1. call showPage(1)
  2. print showing page 1
  3. call preprocessPage(1)
  4. add onclick handler A to .nextPage
  5. click .nextPage
  6. Increment the id in handler A from 1 to 2
  7. Call showPage(2)
  8. print showing page 2
  9. Call preprocessPage(2).
  10. add onclick handler B to .nextPage
  11. click .nextPage
  12. Increment the id in handler A from 2 to 3
  13. Call showPage(3)
  14. print showing page 3
  15. call preprocessPage(3)
  16. add onclick handler C to .nextPage
  17. Increment the id in handler B from 2 to 3
  18. call showPage(3)
  19. print showing page 3
  20. call preprocessPage(3)
  21. add onclick handler D to .nextPage
  22. ...

The following should be closer to what you are looking for

$(document).ready(function() {

    function showPage(id){
      console.log('showing: ' + id);
    }   

    // Start with page 1
    var id = 1;
    // Show the first page
    showPage(id);
    // Add onclick handler to each element with class="nextPage"
    $('.nextPage').click(function(){
         // Increment the page id and then call showPage with the current id
         showPage(++id);
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Hi-I've posted another question that relates: stackoverflow.com/questions/6802641/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.