在jquery中增加变量click()
使用此代码,我正在尝试将click事件动态绑定到元素并引用递增的变量:
$(document).ready(function() { function preprocessPage(id){ $('.nextPage').click(function(){ showPage(++id); }); } function showPage(id){ console.log('showing: '+id); preprocessPage(id); } showPage(1);//init });
show next page
当页面加载时,它似乎按预期工作。 第一次点击似乎有效。 事情变得棘手了。 它似乎多次运行代码(增加2倍)如果你单击div 4次(第一个日志行发生在init加载后),这就是你在firebug控制台中看到的内容:
显示:1
显示:2
显示:3
显示:3
显示:4
显示:4
显示:4
显示:4
显示:5
显示:5
显示:5
显示:5
显示:5
显示:5
显示:5
显示:5
请帮忙! 这是怎么回事? 提前致谢….
每次单击调用show page,向与选择器.nextPage
匹配的元素添加新的onclick处理程序。
有时,在头脑或纸上执行代码以了解正在发生的事情是很好的。 我已经强调了事情失控的事件。
- 电话
showPage(1)
- 打印
showing page 1
- 调用
preprocessPage(1)
- 将onclick处理程序A添加到
.nextPage
- 单击
.nextPage
- 将处理程序A中的
id
从1增加到2 - 致电
showPage(2)
- 打印
showing page 2
- 调用
preprocessPage(2)
。 - 将onclick处理程序B添加到
.nextPage
- 单击
.nextPage
- 将处理程序A中的
id
从2增加到3 - 致电
showPage(3)
- 打印
showing page 3
- 调用
preprocessPage(3)
- 将onclick处理程序C添加到
.nextPage
- 将处理程序B中的
id
从2增加到3 - 电话
showPage(3)
- 打印
showing page 3
- 调用
preprocessPage(3)
- 将onclick处理程序D添加到
.nextPage
- …
以下内容应该更接近您的要求
$(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); }); });