gpt4 book ai didi

php - jQuery 投票系统

转载 作者:可可西里 更新时间:2023-10-31 22:59:29 24 4
gpt4 key购买 nike

所以我正在制作一个投票系统,基本上是一个赞成和反对的投票系统。我正在将 CakePHP 和 jQuery 与 MySQL 一起使用,但想确保前端是正确的,这是最好的方法。

我希望用户能够更改他们的投票,那么利用 jQuery 是最好和最有效的方法吗?在类操作方面,我对 jQuery 还算新手。 p>

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>

最佳答案

你可以这样做:

<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 的需要,并且您不需要加倍的代码来添加当前类。我不确定哪个更快,但我认为这种方式可以更好地维护代码。

关于php - jQuery 投票系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3722874/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com