jQuery使用$ .ajax更改值

时间:2013-01-30 17:22:19

标签: jquery ajax asp-classic each

我有一张这样的表:

<table id="table-name">
    <tr><td id="td-name">something</td></tr>
    <tr><td id="td-name">something</td></tr>
    <tr><td id="td-name">something</td></tr>
    <tr><td id="td-name">something</td></tr>
</table>

我正在尝试使用jQuery来改变“某事”的价值:

$("#table-name #td-name").each(function () {
    $.ajax({
    type: "POST",
    url: "file.asp",
    data: $(this).html()        
    }).done(function r(returnOfASP) {
        $(this).html(returnOfASP);
    });         
});

使用“file.asp”进行数据库查询。 “something”是数据库查询的参数。 “file.asp”正确返回查询,但我无法更改<td>值(html)。我想在Ajax的“完成”中$(this)不正确,但我不知道该怎么做。

3 个答案:

答案 0 :(得分:1)

更改你的jQuery代码:

$("#table-name td").each(function () {
    var self = this;
    $.ajax({
        type: "POST",
        url: "file.asp",
        data: $(this).html()        
    }).done(function r(returnOfASP) {
    $(self).html(returnOfASP);
    });         
});

您不能在页面上有多个ID,这可能会弄乱您的选择器。如果要过滤更多,可以使用类。另外,将this保存到变量可能会解决这个问题。

});

之后,您还有一个额外的$(this).html()不应该在那里

希望这有帮助。

答案 1 :(得分:1)

使用jQuery $.proxy()委派不同上下文中的执行。在你的情况下,它是父母。

$("#table-name #td-name").each(function () {
    $.ajax({
        type: "POST",
        url: "file.asp",
        data: $(this).html()        
    }).done($.proxy(function(response) { $(this).html(returnOfASP); }, this));
});

答案 2 :(得分:1)

你的td需要唯一的id或它应该被称为class。

如果你想循环它们,那就给td类

<table id="table-name">
    <tr><td class="tdName">something</td></tr>
    <tr><td class="tdName">something</td></tr>
    <tr><td class="tdName">something</td></tr>
    <tr><td class="tdName">something</td></tr>
</table>

Javascript测试

$("#table-name .tdName").each(function () {
    // do code in here

    // test output in firebug with
    console.log($(this));
});