我在jQuery上有这个问题投票系统,完美有效:
$(".q_upvote").click(function()
{
var vote = "vote_up";
var question_id = this.id.split('_')[1];
var votedata = "q_vote=" + vote+"&question_id="+question_id;
$.ajax({
type: 'POST',
url: 'vote.php',
data: votedata,
success: function(vote_msg){
if($.trim(vote_msg) == 'ok')
{
$("#votenum").text( parseInt($("#votenum").text()) + 1 ); }
else{
}
}
});
}
)
这是HTML部分:
<p><span id="votenum">{$question_vote}</span>
<a id="upvote_{$qid}" class="q_upvote" href="#"><i class="icon-thumbs-up"></i></a>
我也希望用答案做同样的事情。我写了这个:
$(".a_upvote").click(function()
{
var vote = "vote_up";
var answer_id = this.id.split('_')[1];
votedata = "q_vote=" + vote+"&answer_id="+answer_id;
$.ajax({
type: 'POST',
url: 'vote2.php',
data: votedata,
success: function(vote_msg){
alert(vote_msg)
if($.trim(vote_msg)== 'ok')
{
$("#answervotes").text( parseInt($("#answervotes").text()) + 1 );
}
else{
}
}
});
}
)
这是HTML部分:
{if isset($allanswers) eq True} {section name=res loop=$allanswers}</p>
<div text-align:center;><p> {$allanswers[res].answer_text} </p>
{if isset($smarty.session.username) eq True}
<p><span id = "answervotes">{$allanswers[res].answer_total_rate}</span>
<a id="upvote_{$allanswers[res].answer_id}" class="a_upvote" href="#""><i class="icon-thumbs-up"></i></a>
<a id="downvote_{$allanswers[res].answer_id}" class="a_downvote" href="#" "><i class="icon-thumbs-down" ></i></a></p>
{else}
<p>{$allanswers[res].answer_total_rate}</p>
{/if}
我的问题是如果有几个答案并且用户提出第n个答案,只有第一个号码的投票改变,第n个答案的投票不会改变。我想我需要以某种方式使答案独特,但我不知道如何。我怎样才能解决这个问题? 谢谢。
答案 0 :(得分:1)
首先,您将span
id
设为唯一。通过执行以下操作。
<p><span id = "answervotes{$allanswers[res].answer_id}">{$allanswers[res].answer_total_rate}</span>
然后在你的电话中
$(".a_upvote").click(function()
{
var vote = "vote_up";
var answer_id = this.id.split('_')[1];
votedata = "q_vote=" + vote+"&answer_id="+answer_id;
$.ajax({
type: 'POST',
url: 'vote2.php',
data: votedata,
success: function(vote_msg){
if($.trim(vote_msg)== 'ok')
{
$("#answervotes" + answer_id).text( parseInt($("#answervotes" + answer_id).text()) + 1 );
}
else{
}
}
});
}
)
答案 1 :(得分:1)
我在这里看到的是你有多个具有相同名称answervotes
的ID,因为这是在循环中创建的(如果我没有错),所以它正在更新第一个...
您最好将您的ID更改为类或使其唯一..因为具有相同ID的多个元素无效并且可能会给您带来问题(您现在面临的问题)......
试试这个(在这里将id更改为类)
<p><span class= "answervotes">{$allanswers[res].answer_total_rate}</span>
和你的jquery
$(".a_upvote").click(function()
{
var $this=$(this); //<--here
var vote = "vote_up";
var answer_id = this.id.split('_')[1];
votedata = "q_vote=" + vote+"&answer_id="+answer_id;
$.ajax({
type: 'POST',
url: 'vote2.php',
data: votedata,
success: function(vote_msg){
alert(vote_msg)
if($.trim(vote_msg)== 'ok')
{
$this.siblings(".answervotes").text( parseInt($("#answervotes").text()) + 1 ); //<----here
}
else{
}
}
});
}
)
使用siblings()
,因为您的answervotes
范围和upvote
a位于同一个父<p>