改变图像标签的原型? [英] Alter the prototype of an image tag?

查看:106
本文介绍了改变图像标签的原型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



当图书馆包含在头文件中时,它会改变HTMLImageElement原型,使任何图像用户在HTML中使用的标签,或者在javascript中动态创建的标签将具有由我的库定义的默认onerror函数。



如果任何用户图像无法加载,因为他们指向一个坏网址,我的图书馆会以优雅的方式处理它。



我正在尝试以下一个实验,

  var img = document.createElement('img'); 
img .__ proto __。onerror = function(){
alert('hi');
};
document.body.innerHTML ='< img id =foosrc =bar.png/>'

其中文件bar.png不存在并且不起作用。



但是,如果我只是像

  document.body.innerHTML ='< img id =foosrc =bar.png'+ 
'onerror =this.src = MODIT.getImage(\'blackTile\')。src;/>';

可以正常工作。这里MODIT.getImage()是一个返回图像元素的函数。您可以在此处播放此代码: https://mod.it/ciR_BxqJ/



我正在努力做什么?还有一种方法来全局捕获所有403 GET错误,并以某种方式处理javascript?



谢谢!

解决方案

  window.addEventListener(error,function(e){
if(e&& e.target& ;& e.target.nodeName&& e.target.nodeName.toLowerCase()==img){
alert('Bad image src:'+ e.target.src);
}
},true);

请参阅: http: //jsfiddle.net/Vudsm/


I am trying to write a library that would do the following.

When the library is included in the head, it would alter the HTMLImageElement prototype such that any image tag that the user happened to use in their HTML or that they create dynamically in javascript would have a default onerror function that is defined by my library.

The result of this would be that if any of the users images failed to load because they pointed to a bad url my library would handle it in a graceful way.

I am trying the following just as an experiment,

var img = document.createElement('img');
  img.__proto__.onerror = function() {
    alert('hi');
  };
  document.body.innerHTML = '<img id="foo" src="bar.png"/>'

where the file bar.png does not exist and it does not work.

However if I just do something like

  document.body.innerHTML = '<img id="foo" src="bar.png" ' +
    'onerror="this.src = MODIT.getImage(\'blackTile\').src;"/>';

that works fine. Here MODIT.getImage() is a function that returns an image element. You can play with this code here: https://mod.it/ciR_BxqJ/

Is what I'm trying to do possible? Alternatively is there a way to globally catch all 403 GET errors and handle them with javascript in some way?

Thanks!

解决方案

window.addEventListener("error", function(e) {
    if ( e && e.target && e.target.nodeName && e.target.nodeName.toLowerCase() == "img" ) {
        alert( 'Bad image src: ' + e.target.src);
    }
}, true);

See: http://jsfiddle.net/Vudsm/

这篇关于改变图像标签的原型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆