请看下面的代码
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();
错误消失了。
关于javascript - 无法从 HTML 调用 Javascript 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28040489/