【发布时间】:2014-04-20 20:14:49
【问题描述】:
我有一个 div
<div id='cards'>
我想根据一些逻辑填充图像。但仅当图像首次加载到内存中时。否则,通过onerror我想填写一些文字..
function pasteCard(card, to){
if (typeof(card) == 'string')
card = [card];
var image = [];
for (var i = 0; i < card.length; i++) {
image[i] = new Image();
image[i].src = '/sprites/open/' + card[i] + '.png';
image[i].onload = function() {
pasteImage(to, image[i]);
}
image[i].onerror = function() {
pasteText(to, card[i]);
}
// alert(card[i]) #1
}
function pasteImage(to, image) {
to.append(image);
}
function pasteText(to, text) {
// alert(card[i]) #2
to.append(text);
}
}
pasteCard(['ABC123', 'DEF456', 'GHI789'], $('#cards'));
问题/怪异:If only #2 alert is active it returns nothing. 但奇怪的是if #1 alert is also active it does kinda work...(但仍然无法加载我的图像,并且在涉及其他代码时也大多失败)
问题:为什么没有 #1 警报(至少在那个 jsfiddle 中)就不能工作
建议?:我该怎么办?
【问题讨论】:
-
你的答案在this SO answer。
标签: javascript jquery image dom onerror