Jquery 每个循环不工作
我是 jquery 的新手,但我正在尝试在我的项目中使用它。 我试图循环遍历 #rate_box 内的所有链接并向它们添加单击事件。 这个点击事件会将一些数据发布到外部 php 脚本,然后它应该取消所有链接上的点击事件的绑定(这样人们就不能快速连续评价两次。)然后它应该将从 php 脚本收到的数据放入一个名为#status 的跨度标记。
但是我的代码甚至没有执行警报(“索引:”+ i)。 我绑定正确吗?
<script type="text/javascript">
$(document).ready(function(){
$('#rate_box a').each(function(i) {
$(this).click(function() {
alert("Index: "+i);
$.post("../includes/process/rating.php", {id: "<?php $game_id ?>", type: "game", rating: i+1},
function(data) {
$('#rate_box a').each(function(i) {
$(this).unbind('click');
}
$('#status').html(data).fadeIn("normal");
});
});
});
});
</script>
I'm a newbie to jquery, but am trying to use it in my project.
I'm trying to loop through all the links inside #rate_box and add a click event to them. This click event will post some data to an external php script, and then it should unbind the click events on all of the links (so people cannot rate twice in quick succession.) Then it should put the data recieved from the php script into a span tag called #status.
However my code isn't even executing the alert("Index: "+i). Am I binding it correctly?
<script type="text/javascript">
$(document).ready(function(){
$('#rate_box a').each(function(i) {
$(this).click(function() {
alert("Index: "+i);
$.post("../includes/process/rating.php", {id: "<?php $game_id ?>", type: "game", rating: i+1},
function(data) {
$('#rate_box a').each(function(i) {
$(this).unbind('click');
}
$('#status').html(data).fadeIn("normal");
});
});
});
});
</script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不需要循环遍历单独绑定处理程序的每个链接,您可以这样做:
解除绑定也是如此:
就您的代码而言,它可能不会执行,因为您在解除绑定时尚未关闭内部每个元素标签,因此它是无效的 javascript:
您确实应该使用像 Firebug 或 Firebug Lite 这样的工具来调试您的 javascript,尽管类似上面的东西在大多数浏览器中只会给您一个 Javascript 错误。
编辑如果您想在单击当前链接时查找当前链接的索引,请执行以下操作:
You don't need to loop through each link binding a handler individually, you can just do this:
Same goes for unbinding:
As far as your code, it probably isn't executing because you have not closed the inner each when you are unbinding the element tags, so it is invalid javascript:
You should really use a tool like Firebug or Firebug Lite to debug your javascript, although something like the above should just give you a Javascript error in most browsers.
EDIT If you want to find the index of the current link when it is clicked upon, you do this: