jquery备用链接错误

jquery alternate link onerror?

本文关键字:错误 链接 备用 jquery      更新时间:2023-09-26

我的jquery应用程序在html中包含一个指向托管在服务器上的文档的链接,某些用户无法访问该链接。我可以在另一台服务器上托管该文档的副本。

如果用户无法访问原始文件,我希望将其定向到副本。但如果可能的话,可以访问原件。

我想:

    <a href="http://www.theoriginal.org"     onerror="http://www.thecopy.org">Link</a>

但这一点被忽略了。我看到了很多关于破损图片的问题和答案,但没有看到太多关于其他类型链接的问题和回答。

如果相关,则通过一些javascript插入"原始"链接。

我尝试了建议的Ajax代码,使用谷歌的主页作为我的示例url,但不幸地遇到了这样的问题:"Cross Origin Request Blocked:the Same Origin Policy disallow read the remote resource athttp://www.google.co.nz/.这可以通过将资源移动到同一域或启用CORS来解决。"所以我不能用这种方式来测试页面的存在。

您可以发出ajax请求,并根据响应代码更改链接href

<a class="if-not-working" data-replace-with="http://thecopy.org" href="http://www.theoriginal.org">Link</a>

JS:

$('.if-not-working').each(function(){
  $this = $(this);
  $.ajax({
    type: 'GET',
    'url': $this.attr('href'),
    statusCode: {
      400: function() {
        $this.attr('href', $this.data('replace-with'));
      },
      404: function() {
        $this.attr('href', $this.data('replace-with'));
      },
      500: function() {
        $this.attr('href', $this.data('replace-with'));
      }
    }
  });
});

以下是检查文档是否存在的通用jQuery/ajax代码:

    $.ajax({
    url:'example.html',
    type:'HEAD',
    error: function()
    {
        //file not exists
        $('a').attr('href', 'backup.html');
    },
    success: function()
    {
        //file exists
        $('a').attr('href', ''example.html'');
    }
});

如果你的页面上有很多链接需要备份链接,你可以通过循环浏览页面中的所有链接并在其中传递备份链接来使其成为一个函数,否则循环浏览整个页面就太过分了。