jQuery动态地改变css / text

时间:2013-08-30 06:00:35

标签: jquery spring-mvc

我做错了什么?  我想动态更改div的文本并添加/删除css类到这个div。 “  有几个具有相同名称但不同ID的div

 <div class="mydiv" id="1">Text</div>
 <div class="mydiv" id="2">Text</div> 
 <div class="mydiv" id="3">Text</div> 

 <input type="hidden" name="myfield" id="myfield" value="myvalue" /> 

我正在向Spring MVC控制器发送ajax帖子并完美地得到答案(数据)的真或假。但正如我所看到的那样,它首先生成所有值$(“。mydiv”)。attr(“id”),并且在此成功之后看不到this.id用于改变它的恐惧。我该如何解决这个问题?

$(document).ready(function () {
    $.each($('.mydiv'), function () {
        var code = $(".mydiv").attr("id");

        $.ajax({
            url: '/mycontroller',
            type: 'POST',
            dataType: 'json',
            data: {
                id: $("#myfield").attr("value"),
                codeId: this.id
            },
            success: function (data) {
                if (data == false) {
                    $("#" + this.id).addClass("myNewClass");
                    $("#" + this.id).text("FirstText");
                } else {
                    $("#" + this.id).removeClass("myNewClass");
                    $("#" + this.id).text("SecondText");
                }
            }
        });
    });
});

2 个答案:

答案 0 :(得分:0)

尝试

看起来存在多个问题,从循环开始,ajax成功回调的执行上下文等

$(document).ready(function () {
    $('.mydiv').each(function () {
        //use this.id to get the current elements id - $(".mydiv").attr("id") will give the id of first element with class mydiv
        var code = this.id;

        $.ajax({
            url: '/mycontroller',
            type: 'POST',
            dataType: 'json',
            data: {
                id: $("#myfield").attr("value"),
                codeId: this.id
            },
            success: $.proxy(function (data) {
                //inside the callback this was not pointing the element, here a proxy based soution is used
                //another solution is to assign var self = this; before the ajax request and then instead of this inside the function use self
                if (data == false) {
                    $(this).addClass("myNewClass");
                    $(this).text("FirstText");
                } else {
                    $(this).removeClass("myNewClass");
                    $(this).text("SecondText");
                }
            }, this)
        });
    });
});

答案 1 :(得分:0)

尝试.html()而不是.text()