问题
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.
- call
showPage(1)
- print
showing page 1
- call
preprocessPage(1)
- add onclick handler A to
.nextPage
- click
.nextPage
- Increment the
id
in handler A from 1 to 2 - Call
showPage(2)
- print
showing page 2
- Call
preprocessPage(2)
. - add onclick handler B to
.nextPage
- click
.nextPage
- Increment the
id
in handler A from 2 to 3 - Call
showPage(3)
- print
showing page 3
- call
preprocessPage(3)
- add onclick handler C to
.nextPage
- Increment the
id
in handler B from 2 to 3 - call
showPage(3)
- print
showing page 3
- call
preprocessPage(3)
- add onclick handler D to
.nextPage
- ...
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