我是JavaScript的新手,我想将在HTML文件中创建的按钮连接到单独的JavaScript文件中的函数。现在,我可以在HTML文件中创建脚本并将其链接到按钮,但是无法将其链接到外部JavaScript文件。这是给文字聊天机器人的演讲。
chat.html:
<div id="result"></div>
<script type="text/javascript" src="public/js/stt.js"></script>
<button onclick="startConverting();"><i class="fa fa-microphone"></i></button>
stt.js:
function startConverting () {
if('webkitSpeechRecognition' in window){
var speechRecognizer = new webkitSpeechRecognition();
speechRecognizer.continuous = true;
speechRecognizer.interimResults = true;
speechRecognizer.lang = 'en-IN';
speechRecognizer.start();
var finalTranscripts = '';
speechRecognizer.onresult = function(event){
var interimTranscripts = '';
for(var i = event.resultIndex; i < event.results.length; i++){
var transcript = event.results[i][0].transcript;
transcript.replace("\n", "<br>");
if(event.results[i].isFinal){
finalTranscripts += transcript;
}else{
interimTranscripts += transcript;
}
}
r.innerHTML = finalTranscripts + '<span style="color:#999">' + interimTranscripts + '</span>';
};
speechRecognizer.onerror = function (event) {
};
}else{
r.innerHTML = 'Your browser is not supported. If google chrome, please upgrade!';
}
}
答案 0 :(得分:0)
只需执行require('./ yourfile.js');
将要外部访问的所有变量声明为全局变量。所以代替
var a = "hello" it will be
GLOBAL.a="hello" or just
a = "hello"
来源:Load and execute external js file in node.js with access to local variables?
答案 1 :(得分:0)
删除此语句:-
<script type="text/javascript" src="public/js/stt.js"></script>
最好的方法是创建一个js文件并从该文件导入您的stt.js文件:-
// Load the node-import first.
require('node-import');
var variable = require('public/js/stt.js');
使用上述样式,您的js将运行。
答案 2 :(得分:-1)
将外部文件添加为foolows
<script src="myscripts.js"></script>