繁体   English   中英

无法从HTML调用Javascript类

[英]Unable to call a Javascript class from HTML

请看下面的代码

TTSScript.js

   function TTS()
{
    var msg = new SpeechSynthesisUtterance("yohan");
    var voices = window.speechSynthesis.getVoices();

    this.speakText = function()
        {
             window.speechSynthesis.speak(msg);
        }
    }

的index.html

<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/TTSScript.js"></script>
        <script>
           function speak()
           {
               var msg = new SpeechSynthesisUtterance('Hello World');
               window.speechSynthesis.speak(msg);
           }

           function speak2()
           {
               var TTS = new TTS();
               TTS.speakText();
           }


        </script>
    </head>
    <body>
        <div><button onclick="speak2()">Click me</button></div>
    </body>
</html>

不幸的是,当我单击html页面中的按钮时,我得到的是一个错误。 在下面。

Uncaught TypeError: undefined is not a function (13:42:13:817 | error, javascript)
    at speak2 (public_html/index.html:23:26)
    at onclick (public_html/index.html:31:126)

我对JavaScript不太熟悉,能否让我知道为什么我收到此错误以及如何解决该错误?

声明函数后,其名称将成为(本地)保留的单词。 这意味着使用相同的名称创建变量可能会导致一些问题。

我拿了你的代码并更改了

var TTS = new TTS();
TTS.speakText();

var tts = new TTS();
tts.speakText();

错误消失了。

我解决了你的问题..:

  1. 不要使用所有大写字母名称作为变量

    var tts = new TTS(); tts.speakText();

  2. 拨弄正确的电话

    http://jsfiddle.net/bpprwfxa/4/

 var msg = new SpeechSynthesisUtterance('Yohan'); window.speechSynthesis.speak(msg); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM