Incrementing variable within jquery click()

那年仲夏 提交于 2019-12-11 02:19:38

问题


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:


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);
    });
});


来源:https://stackoverflow.com/questions/6798496/incrementing-variable-within-jquery-click

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!