4

所以我正在制作一个投票系统,基本上是一个竖起大拇指的投票系统。我在 MySQL 中使用 CakePHP 和 jQuery,但想确保前端是正确的,这是最好的方法。

我希望用户能够改变他们的投票,所以使用 jQuery 是最好和最有效的方法吗? 在类操作方面,我对 jQuery 相当陌生。

ID 字段将是用户将投票的照片的唯一 ID。当然,这只是一个测试,不会成为生产中的最终产品。页面上会有多张照片,用户对每张照片投赞成票或反对票。

这是代码。

<?php
echo $javascript->link('jquery/jquery-1.4.2.min',false);
?>
<script type="text/javascript">
    $(document).ready(function() {
        $('.vote').click(function () {
            if ($(this).hasClass("current")) {
                alert("You have already voted for this option!");

                return;
            }
            var parentId = $(this).parent("div").attr("id");
            if ($(this).hasClass("up")) {
                //Do backend query and checking here
                alert("Voted Up!");
                $(this).toggleClass("current");
                if ($("#" + parentId + "-down").hasClass("current")) {
                    $("#" + parentId + "-down").toggleClass("current");
                }
            }
            else if($(this).hasClass("down")) {
                //Do backend query and checking here
                alert("Voted Down!");
                $(this).toggleClass("current");
                if ($("#" + parentId + "-up").hasClass("current")) {
                    $("#" + parentId + "-up").toggleClass("current");
                }
            }



        });
    });
</script>
<div id="1234">
    <a id="1234-up" class="vote up" >+</a> | <a id="1234-down" class="vote down" >-</a>
</div>
4

3 回答 3

5

你可以这样做:

<script type="text/javascript">
    $(document).ready(function() {
        $('.vote').click(function () {
            if ($(this).hasClass("current")) {
                alert("You have already voted for this option!");
            } else {
                var parentId = $(this).parent("div").attr("id");
                var error = false;

                if ($(this).hasClass("up")) {
                    //Do backend query and checking here (SET: error)
                    alert("Voted Up!");
                }
                else if($(this).hasClass("down")) {
                    //Do backend query and checking here (SET: error)
                    alert("Voted Down!");
                }
                //removes all the votes 
                $(this).parent("div").children().removeClass("current");

                if(!error) {
                    $(this).addClass("current");
                } else {
                    alert("There was an error");
                }
            }
            return false;
        });
    });
</script>
<div id="1234">
    <a class="vote up" href="#">+</a> | <a class="vote down" href="#">-</a>
</div>

它消除了对额外 html id 的需要,并且您不需要加倍代码来添加当前类。我不确定哪个更快,但我认为这种方式可以更好地维护代码。

于 2010-09-16T04:26:12.747 回答
0

是的,jQuery 是最好的解决方案,但我不确定您是否可以进一步优化您的代码。

于 2010-09-16T04:17:32.393 回答
0

您可以使用这个:http ://www.technabled.com/2011/02/pulse-lite-reddit-ajax-up-down-voting.html 披露:我是开发人员。

于 2011-02-17T02:37:11.003 回答