[英]Speech Recognition in HTML Forms
我是 javascript 的初學者,我想創建一個接受用戶語音並將其顯示在輸入文本字段中的表單。
<body>
<textarea name="answer1" id="my_field1" cols="80" rows="4"></textarea>
<button onclick="change1()">Change Text</button>
</body>
<script>
function change1(){
var recognition = new webkitSpeechRecognition();
recognition.lang = "en-GB";
recognition.onresult = function(event) {
// console.log(event);
document.getElementById('my_field1').value = event.results[0][0].transcript;
}
recognition.start();
}
</script>
這很好用,但是當我在form
標簽中使用它時它不起作用
<form action="" method="GET">
<textarea name="answer1" id="my_field1" cols="80" rows="4"></textarea>
<button onclick="change1()">Change Text</button>
<br>
<input type="submit" name="" id="">
</form>
<script>
function change1(){
var recognition = new webkitSpeechRecognition();
recognition.lang = "en-GB";
recognition.onresult = function(event) {
// console.log(event);
document.getElementById('my_field1').value = event.results[0][0].transcript;
}
recognition.start();
}
</script>
在這里,當我單擊“更改文本”按鈕時,沒有任何反應,並且 URL 更改了 file:///C:/Users/zjohn/Desktop/sample1.html?answer1=
請告訴我哪里出錯了,以及如何解決這個問題。
單擊按鈕時表單正在提交! 您需要在按鈕上使用preventDefault()
以便它不會提交。
試試下面:
<form action="" method="GET">
<textarea name="answer1" id="my_field1" cols="80" rows="4"></textarea>
<button onclick="preventDefault(); change1();">Change Text</button>
<br>
<input type="submit" name="" id="">
</form>
<script>
function change1(){
var recognition = new webkitSpeechRecognition();
recognition.lang = "en-GB";
recognition.onresult = function(event) {
// console.log(event);
document.getElementById('my_field1').value = event.results[0][0].transcript;
}
recognition.start();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.