Javascript-用文本替换损坏的图像(div;css类)
我试图用JS替换所有损坏的图像。我使用此代码将所有损坏的图像替换为notfound.png图像Javascript-用文本替换损坏的图像(div;css类),javascript,html,css,Javascript,Html,Css,我试图用JS替换所有损坏的图像。我使用此代码将所有损坏的图像替换为notfound.png图像 $(document).ready(function() { $('img').attr('onError', 'this.src="notfound.png"'); }); 无论如何,我想用文字通知代替图片。我找不到正确的方法,非常感谢你的帮助。JS不是我喜欢的咖啡:( 我想将此用于文本部分: 要显示的文本。。。 编辑: 好的,我发现这个解决方案很好用,但是不接受CSS类 <
$(document).ready(function() {
$('img').attr('onError', 'this.src="notfound.png"');
});
无论如何,我想用文字通知代替图片。我找不到正确的方法,非常感谢你的帮助。JS不是我喜欢的咖啡:(
我想将此用于文本部分:
要显示的文本。。。
编辑:
好的,我发现这个解决方案很好用,但是不接受CSS类
<script type="text/javascript">
$(document).ready(function() {
$('.post_body img').one('error', function() {
$(this).replaceWith('<div>Image not found (error 404)</div>').addClass('error404');
});
});
</script>
您可以创建文本节点并将其附加到
img
的父节点,如果需要,还可以选择删除img
。此代码位于img
的错误处理程序中
$('img').on('error', function(){
$(this).parent().append($('<div>Broken image</div>'));
$(this).remove();
})
$('img')。在('error',function()上{
$(this.parent().append($('breaked image'));
$(this.remove();
})
如果您确实需要使用javascript进行此操作,请尝试
$(document).ready(function() {
$('img').attr('alt', 'Alternative text');
});
但是,赤裸裸的HTML也可以做到这一点
<img src="path/to/image.jpg" alt="Alternative text">
如果抛出错误,您可以更改alt,就像处理图像一样
function imgMissing(image) {
image.onerror = "";
image.alt = "Image not Found";
return true;
}
HTML:
<img src="image.jpg" onerror="imgMissing(this);" >
编辑:好的,我发现这个解决方案运行良好:
<script type="text/javascript">
$(document).ready(function() {
$('.post_body img').one('error', function() {
$(this).replaceWith('<div>Image not found (error 404)</div>');
});
});
</script>
好的,我想我已经为您找到了一个解决方案。我尝试使用jQuery函数。这个函数帮助了我:
要用另一个映像替换所有缺少的映像,可以更新传递给.error()的回调中的src属性。请确保替换映像存在;否则将无限期触发错误事件
在您的示例中,这是最好的:
$('img').each(function() {
var img = $(this);
img.error(function() {
img.replaceWith('<div class="error404">Image not found (error 404)</div>');
}).attr('src', img.attr('src'));
});
$('img')。每个(函数(){
var img=$(本);
img.error(函数(){
img.replaceWith('未找到图像(错误404)');
}).attr('src',img.attr('src');
});
我还为你做了一个,这对我来说非常有用。这样代码将是$(这个)。replaceWith('Image not found(error 404)).addClass('error 404');
?$(这个)。replaceWith('Image not found(error 404))。addClass('error 404');
看看我的答案,我为你找到了一个解决方案。
.error404 {
display: block;
color: #667d99;
font-weight: bold;
font-size: 11px;
border: 1px dotted;
border-radius: 3px;
padding: 5px;
margin: 10px;
background: #e7edf3;
}
$('img').each(function() {
var img = $(this);
img.error(function() {
img.replaceWith('<div class="error404">Image not found (error 404)</div>');
}).attr('src', img.attr('src'));
});