Jquery每个循环都不起作用

时间:2009-04-01 03:45:22

标签: javascript jquery ajax bind

我是jquery的新手,但我正在尝试在我的项目中使用它。 我正在尝试循环遍历#rate_box中的所有链接并向其添加点击事件。这个点击事件会将一些数据发布到一个外部的PHP脚本,然后它应解除所有链接上的点击事件(所以人们不能快速连续两次。)然后它应该将从PHP脚本收到的数据放入一个span标签名为#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>

1 个答案:

答案 0 :(得分:5)

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

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

});

解除绑定也是如此:

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

就你的代码而言,它可能没有执行,因为当你解开元素标签时你还没有关闭内部,所以它是无效的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'); 
    });
});
相关问题