【问题标题】:onerror is working on ng-src but not on anchor tagonerror 正在处理 ng-src 但不在锚标记上
【发布时间】:2016-09-19 06:30:54
【问题描述】:

Obective : 如果没有可用的图像,则在锚标记上显示默认图像

onerror 正在处理 ng-src 但不是

不工作

<li class=""><a href="http://imagepath/correct.jpg" id="hrefID"      onerror="this.src='http://imagepath/default.jpg'  "title="default image"</a>

这是有效的,但不可点击

  <img alt="1" ng-   src="http://imagepath/correct.jpg" onerror="this.src='http://imagepath/default.jpg '"title="default image" />

【问题讨论】:

  • onerror is working on ng-src but not not working 是什么意思?
  • 它可以工作 imagepath/correct.jpg" onerror="this.src='imagepath/default.jpg '"title="default image" /> 但不能一个可点击的锚标签 目标:如果没有可用的图像,则在锚标签上显示默认图像hrefID" onerror="this.src='imagepath/default.jpg'
  • onerror on img 经常出错。最好选择这里讨论的指令之一,stackoverflow.com/questions/16349578/…

标签: javascript


【解决方案1】:

Angular 指令 ngSrc 没有任何用于处理 404 响应的本机功能。

所以你可以这样尝试:

<div ng-controller="MyCtrl">
    <div ng-repeat="image in images">
        <img ng-src="{{image}}" on-error="http://google.com/favicon.ico"/>
    </div>
</div>


<script>
var myApp = angular.module('myApp',[]);

myApp.directive('onError', function() {
  return {
    link: function(scope, element, attrs) {
      element.bind('error', function() {
        if (attrs.src != attrs.onError) {
          attrs.$set('src', attrs.onError);
        }
      });
    }
  }
});

myApp.controller("MyCtrl", function($scope) {
    $scope.images = [
        'http://www.titanui.com/wp-content/uploads/2013/11/30/Flat-AngularJS-Logo-PSD.png',
        'any.png' //WRONG URL
    ];
});
</script>

Fiddle

【讨论】:

  • 使用 ng-src 完美地工作 onerror="this.src='image/path'" 只是不知道锚标记的等效 onerror 语法,即 this.href= ???
  • onerror 不适用于锚标记。我在 上工作
猜你喜欢
  • 1970-01-01
  • 2016-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-14
  • 2016-09-01
相关资源
最近更新 更多