一个错误事件添加一个新类并计算它替换图像源的次数

Onerror event add a new class and count how many times it replaces image source

本文关键字:一个 图像 替换 新类 事件 错误 添加 计算      更新时间:2023-09-26

我使用onerror功能来检测断开的链接并用图像替换它们,问题是在我的代码中,可以点击的图像。

所以我想用这种方式,当函数imageOnError被调用时,使图像无法点击。我试着这样做(img).unbind("click");也喜欢这个:img.class = "blocked";

但它不起作用?

<img  class="img img-click not-selected " src="" onerror="return imageOnError(this);" />
countImgReplaced = 0;
function imageOnError(img) {
    img.onerror = '';
    img.src = 'https://dummyimage.com/256x256?text=Broken%20images%20.';
    (img).unbind("click");
     countImgReplaced ++;
    return true;
}

我还想得到图像被替换的次数,我用countImgReplaced做了这个,但它给了我图像的总数:/

我真的很困惑。有人能帮我吗?

您可以通过类将pointer-events: none;应用于它们。您可以使用classList API 来应用它

img.classList.add('blocked');

您可以在HTML标记中执行此操作。

<img  src="../resources/images/Image1.jpg" onerror="this.src='https://www.google.co.in/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png';this.style='pointer-events: none'" />

$(document).ready(function(){
  $("img").click(function(){
     alert("Valid");
  });
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="clear:both;"><lable>Click in image(Invalid img):</lable>
<img width=200px height=200px src="../resources/images/Image1.jpg" onerror="this.src='https://www.google.co.in/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png';this.style='pointer-events: none'" />
</div>
<div style="clear:both;"><lable>Click in image (Valid img):<lable>
<img width=200px height=200px src="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQzltPjpuUfCzEsYbhTYTm4xab4wfmCTFoNllbU5ljLLEAb3VvJXkgpWvU" onerror="this.src='https://www.google.co.in/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png';this.style='pointer-events: none'" /></div>