1

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

但是我的代码甚至没有执行 alert("Index: "+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>
4

1 回答 1

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 ");"

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:

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'); 
    });
});
于 2009-04-01T03:47:27.663 回答