javascript - Jquery 每个循环不工作

标签 javascript jquery ajax bind

我是 jquery 的新手,但我正在尝试在我的项目中使用它。 我试图遍历 #rate_box 内的所有链接并向它们添加点击事件。这个点击事件会将一些数据发布到外部 php 脚本,然后它应该解除绑定(bind)所有链接上的点击事件(这样人们就不能快速连续评价两次。)然后它应该将从 php 脚本接收到的数据放入一个名为 #status 的 span 标签。

但是我的代码甚至没有执行 alert("Index: "+i)。我是否正确绑定(bind)了它?

<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>

最佳答案

您不需要循环遍历每个单独绑定(bind)处理程序的链接,您可以这样做:

// bind click handler to all <a> tags inside #rate_box
$('#rate_box a').click(function() {

});

解除绑定(bind)也是如此:

$('#rate_box a').unbind('click');

就您的代码而言,它可能没有执行,因为您在取消绑定(bind)元素标签时没有关闭内部 each,因此它是无效的 javascript:

$('#rate_box a').each(function(i) {
    $(this).unbind('click');
} // <- missing closing ");"

你真的应该使用像 Firebug 或 Firebug Lite 这样的工具来调试你的 javascript,尽管像上面这样的东西在大多数浏览器中只会给你一个 Javascript 错误。

编辑 如果你想在点击时找到当前链接的索引,你可以这样做:

var links = $('#rate_box a');
$(links).click(function() {
    // this is to stop successive clicks on ratings,
    // although the server should still validate to make
    // sure only one rating is sent per game
    if($(this).hasClass('inactive_for_click')) return false;
    $(links).addClass('inactive_for_click');
    // get the index of the link relative to the rest, add 1
    var index = $(links).index(this) + 1;
    $.post("../includes/process/rating.php", {
        id: "<?php $game_id ?>",
        type: "game",
        rating: index
    }, function(data) {
        $('#status').html(data).fadeIn("normal");
        // unbind links to disable further voting
        $(links).unbind('click'); 
    });
});

关于javascript - Jquery 每个循环不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/703983/

相关文章:

javascript - 多次promise后需要返回结果

javascript - jQuery td :contains

javascript - 当 session 下拉字段选择的文本是管理员时,jQuery 验证不会触发所需的条件?

java - 服务器端java用于处理Ajax请求

javascript - 在 ASP.NET 中使用 javascript 进行检查时,如何传递复选框的值和相应的名称?

javascript - 修改 PHP 函数以在操作后重定向

javascript - 管理 splitterSide 以将其用作可重用组件

javascript - 根据当前时间加载 YouTube 视频?

c# - 无法在 C# MVC 中返回具有不同参数的 View() - Ajax 问题更新页面内容

javascript - 如何在 Javascript 中实现 Haskell 的 FRP Behavior 类型?