【发布时间】:2012-01-27 15:36:10
【问题描述】:
出于某种原因(可能是因为我不懂闭包)函数inResult 总是返回false 并且循环永远不会执行。当然,我确信result contains 具有正确的属性。
function hasId() {return $(this).prop('id');}
function inResult(res) { return res.hasOwnProperty($(this).prop('id'));}
$.ajax({
url : opt.url,
data : $.extend(true, opt.data, {ids: ids}),
context : this, // A collection of elements
type : 'POST',
dataType : 'json',
success : function(result) {
// Filter elements with id and with a property in result named "id"
this.filter(hasId).filter(inResult(result)).each(function() {
console.log($(this).prop('id'));
});
}
});
编辑:工作代码解决方案(感谢 Šime Vidas 为我指明了正确的方向):
// Use closures to change the context later
var hasId = function() { return $(this).prop('id'); };
var inResult = function(res) { return res.hasOwnProperty($(this).prop('id')); };
$.ajax({
url : opt.url,
data : $.extend(true, opt.data, {ids: ids}),
context : this, // A collection of elements
type : 'POST',
dataType : 'json',
success : function(result) {
// Filter elements with id and with a property in result named "id"
var filtered = this.filter(function() {
// Note the context switch and result parameter passing
return hasId.call(this) && isBinded.call(this, result);
});
filtered.each(function() { console.log($(this).prop('id')); });
}
});
【问题讨论】:
-
this.id工作正常。不需要prop()。 -
@ŠimeVidas 谢谢你的提示。
-
闭包不是 jQuery 特有的,它们是 JavaScript 特性之一。
-
@zizozu 你说得对,感谢编辑。
标签: javascript jquery closures