c# - 帮助 jQuery 投票系统。无法更新 html 投票计数

标签 c# jquery asp.net-mvc json voting

我正在尝试创建一个类似 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/

相关文章:

c# - 在 Ninject 中停用时跳过 Dispose

c# - 多个带有代理的 HttpClients,试图达到最大下载速度

javascript - 如何在单个 jQuery 对象上执行函数?

asp.net-mvc - 如何捕获ASP.NET MVC中未处理的错误?

asp.net-mvc - 没有给出对应于 'key' 的必需形式参数 'IOwinContext.Get<T>(string)' 的参数

c# - 是否可以从 Controller 方法以编程方式调用 Razor 编译器?

c# - 聚合 C# 数据集时,如何将 DataSet 转换为 .Load() 的 DataTable 数组?

javascript - 似乎无法让 jQuery .on 启动

javascript - 如何根据其内容的大小将 iFrame 设为 'grow'?

c# - ViewModel 不包含电子邮件的定义