一个jQuery事件绑定的问题
对于网页中的所有p元素,当第一次单击时弹出“您是第一次访问”。当以后每次单击时,则弹出“欢迎您再次访问”。请用jQuery代码实现。我用下面的代码为什么不对呢,请好心人告诉我哦
<script src="jquery.min.js"></script>
<script>
$(document).ready(function(){
function fnclick1(){
alert("欢迎您第一次访问");
$("p").unbind("click",fnclick1);
$("p").bind("click",function(){
alert("欢迎您再次访问");
})
}
$("p").one("click",fnclick1)
})
</script>
</head>
<body>
<p>演示1</p>
<p>演示2</p>
<p>演示3</p>
</body>
[解决办法]
最简单就是 定义一个全局变量
<script src="http://code.jquery.com/jquery-latest.js"></script><script>$(document).ready(function(){ var flag = false; $('p').click(function(){ if( flag ){ alert('欢迎再次访问'); } else { alert('欢迎访问'); flag = true; } })})</script></head><body><p>演示1</p><p>演示2</p><p>演示3</p></body>
[解决办法]
<!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="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script><script type="text/javascript">$(document).ready( function() { $("p").click( function() { var viewCount = $(this).attr("viewCount"); if (viewCount == undefined) { alert('欢迎您第一次访问'); $(this).attr("viewCount", 1); } else { alert('欢迎您再次访问'); $(this).attr("viewCount", (parseInt(viewCount) + 1)); } });});</script></head><body><p>演示1</p><p>演示2</p><p>演示3</p></body></html>
[解决办法]
楼主的方法:
$(document).ready(function() { function fnclick1() { alert("欢迎您第一次访问"); $(this).unbind("click", fnclick1); $(this).bind("click", function() { alert("欢迎您再次访问"); }) } $("p").one("click", fnclick1);});