在窗口加载时,我试图检查我的图像是否已经保存,如果是,则更改HTML以便禁用保存它的链接。此代码类型在没有.each()
的情况下工作,但仅查找第一个标记并基于此更改所有其他类似标记。当然我想分别做每个标签。通过查看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");
});
});
}
答案 0 :(得分: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调用可能是一个更好的主意,但是要传递一个文件列表以进行检查,然后处理将引用所有这些图像的响应(逐个)
答案 1 :(得分:1)
javascript闭包中有一些规则。
有时在不同的闭包中this
是不同的参考。
尝试
var that = $(this);
并使用that
为您需要的项目参考
答案 2 :(得分: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");
});
});
}
希望有所帮助。
答案 3 :(得分: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");