1、这是一段重复执行的代码,每当你点一次,就会自动增加一次事件的调用。<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><script type="text/javascript" src="js/jquery.js"></script><script type="text/javascript"> function tips(){ $('#yy').click(function(){ say($('#txt').val()); }); } function say(msg){ var str = '这是我想说的提示:'+msg; alert(str); tips() } $(document).ready(function(){ tips(); });</script></head><body><input type="text" id="txt" value="" /><input type="button" id="yy" value="yyy" /></body></html>
2、事实上这不是我们想要的执行结果对吧,我们只需要点击一次就运行一次就完事,针对于此,jquery 有一个unbind 的函数能够帮助我们实现。
3、把代码改为如此,就能成功成你所愿了。<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>无标题文档</title><script type="text/javascript" src="js/jquery.js"></script><script type="text/javascript"> function tips(){ $('#yy').unbind('click').bind('click',function(){ say($('#txt').val()); }); } function say(msg){ var str = '这是我想说的提示:'+msg; alert(str); tips() } $(document).ready(function(){ tips(); });</script></head><body><input type="text" id="txt" value="" /><input type="button" id="yy" value="yyy" /></body></html>
4、这虽然很简单,但是这个例子很容让人疏忽,如果是弹框是容易发现是重复的,如果是获取数据呢?这不是增大很多服务器的压力吗?