出于某种原因(可能是因为我不理解闭包)函数 inResult
总是返回 false
并且循环永远不会执行。当然,我确信 result
包含正确的属性。
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.filter( hasId ).filter( function () {
return inResult( result );
}).each( function () {
console.log( this.id );
});
在您的代码中,您有 .filter(inResult(result))
这将不起作用,因为您正在立即调用 inResult
并传递 result 该调用(这是一个 bool 值)到 filter()
,它不适用于 bool 值。
你也可以这样做:
var keys = Object.keys( result );
var filtered = this.filter( function () {
return this.id && keys.indexOf( this.id ) > -1;
});
Object.keys( result )
从 result
返回所有自己的属性名称的数组。
关于javascript - 理解闭包和作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9035841/