开发者

Hide input="image" if image src not found

I'm using the following JavaScript function to hide images on my webpage in the event that the source image is not found:

function Image_OnError(image) {
    image.onerror = "";
    image.style.visibility = "hidden";
    return true;
}

I add the following attribute to my images which calls the above method in the event of an error onerror="Image_OnError(this);".

The problem is that I need to do the same for <input type="image" /> elements but can't figure out how to do this as the input element doesn't appear to have an OnError event.

I could just include an extra image with the same src value as the input and then modify the visibility of the input element on the image's OnError event, but this seems a bit me开发者_JS百科ssy.


If you'd like a semi-hack, you can use jQuery's "document.ready" event, and check the height of the input.

EDIT: In response to you're answer to Aviator's question above... You could just use an asp:LinkButton, and wrap an image inside of it as content... and then use the OnCommand event of the LinkButton.


It has same onerror event. This one works for me (in chrome at least):

<input type="image" onerror="alert(1);" src="http://xxx" />

Another possible way is to load image in JS:

on document load:

$('input[type="image"]').each(function(){
    var img = new Image();
    var input = this;
    img.onerror = function() { Image_OnError(input); }
    img.src = this.src;
})

Also, you'd better hide them from the start and show only elements with image loaded successfully. Otherwise you'll probably have elements jumping on the page.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜