Javascript`onerror`没有被解雇

时间:2015-01-23 07:10:01

标签: javascript html web javascript-events onerror

请查看以下代码

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>

然而,这会产生以下错误,即使它应该处理它。

Failed to load resource: the server responded with a status of 404 (Not Found) (12:49:15:455 | error, network)
  at http://www.translate.google.com/translate_tts?tl=en&q=hello

我想要做的是,如果发生此错误,我想在var url2中使用var url代替function longSentenceSpeak(text)。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

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>