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....