【问题标题】:Javascript `onerror` is not getting firedJavascript`onerror`没有被解雇
【发布时间】:2015-01-23 07:10:01
【问题描述】:

请看下面的代码:

function longSentenceSpeak(text)
    {

        var url = "http://www.translate.google.com/translate_tts?tl=en&q="+finalString;
        var url2 = "http://www.translate.google.com/translate_tts?tl=sp&q="+finalString;

        var audio = document.getElementById('audio');

        var source = document.getElementById('source');
        source.src=url;

        audio.load(); //call this to just preload the audio without playing
        audio.play(); //call this to play the song right away

    audio.onerror = function()
    {
        var url2 = "http://translate.google.com/translate_tts?tl=en&q="+text;

        var audio = document.getElementById('audio');

        var source = document.getElementById('source');
        source.src = url2;

        audio.load(); //call this to just preload the audio without playing
        audio.play(); //call this to play the song right away
    };
    }

下面是我的 HTML:

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <script src="scripts/TTS.js"></script>
        <script>
           function longText()
           {
               longSentenceSpeak("hello world ");
           }
        </script>
    </head>
    <body>
        <audio id="audio">
            <source id="source" src="" type="audio/mp3" />
        </audio>

        <div><button onclick="longText()">Click me</button></div>
    </body>
</html>

然而这会产生这个错误,即使它应该处理它:

加载资源失败:服务器响应状态为 404(未找到)(12:49:15:455 | 错误,网络)
在 http‍://www.translate.google.com/translate_tts?tl=en&q=hello

我想做的是,如果发生此错误,我想在function longSentenceSpeak(text) 中使用var url2 而不是var url。我该怎么做?

【问题讨论】:

  • 尝试将第一个调用包装在try 块中,并在case 块中调用第二个函数
  • @KirillPisarev:我也试过了。
  • 好的,mb onstalled 处理程序?当浏览器试图获取媒体数据,但数据不可用时,会发生停滞事件。
  • @KirillPisarev: 怎么用?
  • 只需将onerror 更改为onstalled

标签: javascript html dom-events onerror


【解决方案1】:

error 事件不会冒泡,在这种情况下,它将在 元素上触发。
因此,您需要从那里收听:

function longText() {

  var audio = document.getElementById('audio');

  var source = document.getElementById('source');
  source.src = '/foo.bar';
  audio.load(); //call this to just preload the audio without playing
  audio.play(); //call this to play the song right away

  source.onerror = function() {
   console.log('handling error event');
  };
  
}
<audio id="audio">
  <source id="source" src="" type="audio/mp3" />
</audio>

<div><button onclick="longText()">Click me</button></div>

【讨论】:

    猜你喜欢
    • 2020-03-28
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 2016-07-15
    相关资源
    最近更新 更多