0

在窗口加载时,我正在尝试检查我的图像是否已保存,如果已保存,请更改 HTML 以禁用保存它的链接。这种代码类型可以在没有.each()with 的情况下工作,但只会找到第一个标签并根据它更改所有其他类似的标签。当然,我想分别做每个标签。通过查看 firebug 中的 post 事务,每个 ajax 调用都正确处理并发送了正确的href值,但 html 更新似乎没有采取。if 语句没有失败,因为警报消息在它应该出现的时候出现。知道为什么$(this)可以检索项目值但在设置 html 更改时不起作用?

window.onload =  function() {
    $(".img a").each(function() {
        var item=$(this).attr( 'href' );
        var action="check";
        jqxhr = $.post("webservice.php", { action: action, color: item }, function(data) {
            var result=data.result;
            if (result=="saved") {
                $(this).html("<div style='line-height:4em '>Saved</div>");
                $(this).attr("href","saved");
                alert(result);
            }

        }, "json")
        .error(function() {         
            alert("error: unable to contact web service"); 
        });
    });
}
4

4 回答 4

2

问题是this回调内部没有引用你认为的元素。

您需要在 ajax 之前创建对该元素的引用并使用它。

window.onload =  function() {
    $(".img a").each(function() {
        var self   = $(this),
            item   = this.href,
            action = "check";
        jqxhr = $.post("webservice.php", { action: action, color: item }, function(data) {
            var result=data.result;
            if (result=="saved") {
                self.html("<div style='line-height:4em '>Saved</div>");
                self.attr("href","saved");
                alert(result);
            }

        }, "json")
        .error(function() {         
            alert("error: unable to contact web service"); 
        });
    });
}

此外,运行这么多 ajax 调用来检查类似的事情似乎有点过头了。
重构代码以进行单个 ajax 调用可能是一个更好的主意,但将文件列表传递给它以检查然后处理将引用所有这些图像的响应(一个接一个

于 2012-11-08T12:34:15.863 回答
1

javascript 闭包中有一些规则。有时在不同的闭包this中是不同的参考。

尝试

var that = $(this);

that在您需要的任何地方使用项目参考

于 2012-11-08T12:34:23.073 回答
1

成功方法的调用者不是<a>元素。

window.onload =  function() {
$(".img a").each(function() {
    var $this = $(this);
    var item=$(this).attr( 'href' );
    var action="check";
    jqxhr = $.post("webservice.php", { action: action, color: item }, function(data) {
        var result=data.result;
        if (result=="saved") {
            $this.html("<div style='line-height:4em '>Saved</div>");
            $this.attr("href","saved");
            alert(result);
        }

    }, "json")
    .error(function() {         
        alert("error: unable to contact web service"); 
    });
});
}

希望有帮助。

于 2012-11-08T12:34:23.633 回答
1

尝试改变:

var item=$(this).attr( 'href' );

至:

var $item = $(this);
var item=$item.attr( 'href' );

然后改变:

$(this).html("<div style='line-height:4em '>Saved</div>");
$(this).attr("href","saved");

至:

$item.html("<div style='line-height:4em '>Saved</div>");
$item.attr("href","saved");
于 2012-11-08T12:35:57.377 回答