我仍在尝试从嵌套的回调函数内部函数返回值,但已经用尽了想法。
这是代码:
function addListener() {
var imgs = document.getElementsByClassName('img');
var ids = document.getElementsByClassName('item');
for (let i = 0; i < imgs.length; i++) {
let img = imgs[i];
img.addEventListener('click', function() {
var card_1 = function getId() {
var Id = ids[i].id;
return Id;
};
img.style.opacity = "1.0";
window.setTimeout(function() {
img.style.opacity = "0.0"
}, 2000)
});
}
}
谢谢!
答案 0 :(得分:0)
您很有可能需要使用回调,因此无法从该函数返回值,因为该函数所做的工作是异步的:
function addListener(cb) {
var imgs = document.getElementsByClassName('img');
var ids = document.getElementsByClassName('item');
for (let i = 0; i < imgs.length; i++) {
let img = imgs[i];
var Id = ids[i].id;
img.addEventListener('click', function() {
cb(null,Id); // use an error-first callback
img.style.opacity = "1.0";
window.setTimeout(function() {
img.style.opacity = "0.0"
}, 2000)
});
}
}
这样调用函数:
addListener(function(err,id){
});