【问题标题】:Issue with .on('error').on('error') 的问题
【发布时间】:2018-05-23 04:29:25
【问题描述】:

如果'src'返回错误,我想从'.check-img'中获取'data-defaulting',然后将值分配给其兄弟源的src。

这个想法是检查移动版本图像是否可用,如果没有,则采用默认值并通过将其作为 srcset 分配给移动源来在移动设备中显示默认图像。

这似乎不起作用,并且重复发生对不存在的图像的请求。

<picture>

    <!-- Mobile image -->
    <source srcset="data-defaultimg value should be here if .check-img (mobile image src) returns error" media="(max-width:768px)">

    <!-- Virtual image with desktop image as data-defaultImage value --> 
    <img style="display: none" src="mobile image src here" alt="" class="check-img" data-defaultimg="default src here">

    <!-- Desktop image. -->
    <img src="desktop-img-src" alt="" class="img-fluid">

</picture>

用于检查错误并将“defaultimg”值分配给移动图像srcset的jQuery。

$("picture img.check-img").each(function(){
  $(this).on('error', function(){
    $(this).siblings("source").attr("srcset", $(this).data('defaultimg'));
  })
});

我不确定为什么丢失的图像请求会继续进行。请帮忙。谢谢。

【问题讨论】:

  • 显示:没有图像甚至可能无法下载
  • 是的,只要删除display: none;,图像甚至没有加载,这就是它永远不会失败的原因。
  • 尝试删除 'display: none',但还是一样。
  • 好的,我检查一下
  • 我复制它并且它有效。您遇到了什么错误?

标签: jquery


【解决方案1】:

为避免重复加载未找到的图像,只需在处理完错误后移除错误事件即可。

$("picture img.check-img").each(function() {
  $(this).on('error', function() {
    $(this).off('error');
    $(this).siblings("source").attr("srcset", $(this).data('defaultimg'));
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<picture>

    <!-- Mobile image -->
    <source srcset="" media="(max-width:768px)">

    <!-- Virtual image with desktop image as data-defaultImage value --> 
    <img style="display: none" src="does/not/exist.jpg" alt="" class="check-img" data-defaultimg="https://pbs.twimg.com/profile_images/420241225283674113/xoCDeFzV_400x400.jpeg">
    
    <!-- Desktop image. -->
    <img src="desktop-img-src" alt="" class="img-fluid">

</picture>

【讨论】:

    猜你喜欢
    • 2020-05-27
    • 2017-01-30
    • 2020-07-30
    • 1970-01-01
    • 2012-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多