【问题标题】:Using onerror on an iframe在 iframe 上使用 onerror
【发布时间】:2018-10-04 05:22:03
【问题描述】:

如果链接断开或不存在,下面的 sn-p 会将 PNG 图像替换为 GIF 图像。我试图在 iframe 上应用它,但它似乎不起作用。这甚至可能吗?

<html>

	<body>

	<iframe src="index1.html" onerror="this.onerror=null;this.src='https://media.giphy.com/media/3oEjI6SIIHBdRxXI40/giphy.gif';"> </iframe>
	<img src="test.png" onerror="this.onerror=null;this.src='https://media.giphy.com/media/3oEjI6SIIHBdRxXI40/giphy.gif';" />

	</body>

</html>

非常感谢您的回复。提前致谢! :)

【问题讨论】:

  • 可以单独使用JS查看链接是否存在 display id_a else display id_b
  • 嗨 Muhammed,我有一个想法,javascript 可以做到这一点,但我不确定如何执行它

标签: javascript html css onerror


【解决方案1】:

如果在加载外部文件(例如文档或图像)时发生错误,则会触发 onerror 事件。

iframe 内容不是文件,因此不会触发 onerror。您可以使用 JS 来检查是否收到 HTTP 成功响应(200)。

var myRequest = new Request('index1.html');

fetch(myRequest).then(function(response) {
  console.log(response.status); // returns 200
}).catch(function(error) {
  document.getElementById("iframe-id").src = "/your/file/path/here/somePage.html";
});
<iframe id="iframe-id" src="index1.html"> </iframe>
<img src="test.png" onerror="this.onerror=null;this.src='https://media.giphy.com/media/3oEjI6SIIHBdRxXI40/giphy.gif';" />

【讨论】:

  • 谢谢 itay 但是如果链接在 iframe 中不存在,我怎样才能使页面重定向?
  • 你试过了吗?特定的网址显然不起作用,您需要将其替换为您现有的真实网址
  • 是的,我在本地尝试过,它似乎一直在加载这一行中说明的 src:document.getElementById("iframe-id").src = "/your/file/路径/这里/somePage.html";即使 url 存在于同一个文件夹中。
猜你喜欢
  • 1970-01-01
  • 2017-04-13
  • 2015-06-15
  • 1970-01-01
  • 1970-01-01
  • 2015-10-30
  • 1970-01-01
  • 2013-03-13
  • 1970-01-01
相关资源
最近更新 更多