jQuery voting system

亡梦爱人 提交于 2019-11-28 09:30:11

You could do it this way:

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

It removes the need for extra html id's and you dont need the doubled up code to add the current class. I'm not sure which is quicker, but I think this way will allow better code maintenance.

Yes, jQuery is the best solution for this but I'm not sure if you can optimize your code any more so.

You can use this one: http://www.technabled.com/2011/02/pulse-lite-reddit-ajax-up-down-voting.html Disclosure: I am the developer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!