我正在尝试创建一个类似 Stackoverflow 的投票系统,但我遇到了一个小问题。
我有以下 HTML,其中连接了 jQuery onClick 事件:
<div id="c_<%=Html.Encode(Model.C.cID) %>" class="votes">
<img src="../../Content/gfx/Up.png" class="up" alt="" />
<span class="votecount"><%= Html.Encode(Model.C.VoteCount)%></span>
<img src="../../Content/gfx/Down.png" class="down" alt="" />
</div>
jQuery onClick 看起来像这样:
$(".up").click(function() {
var id = $(this).parent().attr("id").split("_");
if (id[0] == "c") {
//C Vote
//id[1] contains the id number.
$.post("/Vote/CUp", { id: id[1] }, function(data) {
$(this).parent().children(".votecount").html(data.voteCount);
},
"json"
);
} else {
//R Vote
$.post("/Vote/RUp", { id: id[1] }, function(data) {
$(this).parent().children(".votecount").html(data.voteCount);
},
"json"
);
};
});
我的问题在于尝试更新投票数。我只是不知道如何使用 JSON 对象中返回的值更新投票计数范围。
JSON 对象正在返回数据,我已经使用 alert(data) 验证了这一点
非常感谢您的帮助。
最佳答案
在 $.post() 回调的范围内,this 将为您提供对 XMLHttpRequest 对象的引用,而不是引发早期点击事件的元素。
您可以将 this 分配给点击处理程序范围内的变量,并且它在 $.post() 的回调中仍然可用。像这样:
$(".up").click(function() {
var id = $(this).parent().attr("id").split("_");
// Due to the awesome magic of closures, this will be available
// in the callback. "el" is a weak name for the variable, you
// should rename it.
var el = this;
if (id[0] == "c") {
//C Vote
//id[1] contains the id number.
$.post("/Vote/CUp", { id: id[1] }, function(data) {
// siblings() is an easier way to select that.
$(el).siblings(".votecount").html(data.voteCount);
}, "json");
} else {
//R Vote
$.post("/Vote/RUp", { id: id[1] }, function(data) {
$(el).siblings(".votecount").html(data.voteCount);
}, "json");
};
});
关于c# - 帮助 jQuery 投票系统。无法更新 html 投票计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1643822/