在JavaScript的相同功能上使用多个按钮

时间:2018-11-25 18:11:05

标签: javascript php html

我想为使用相同功能但存储在不同ID名称上的不同文本框创建多个按钮。

Name<input id="name"></input>
<button onclick="myFunction()">Start</button>

<script>
    function myFunction() {
        var recognition = new (window.SpeechRecognition || 
        window.webkitSpeechRecognition || window.mozSpeechRecognition || 
        window.msSpeechRecognition)();
        recognition.lang = 'en-US';
        recognition.interimResults = false;
        recognition.maxAlternatives = 5;
        recognition.start();
        recognition.onresult = function(event) {
           document.getElementById("name").value =(event.results[0][0].transcript);
         };
    }
</script>

1 个答案:

答案 0 :(得分:3)

像这样调用函数时传递输入字段的ID

Name<input id="name"></input>
<button onclick="myFunction('name')">Start</button>

Phone<input id="phone"></input>
<button onclick="myFunction('phone')">Start</button>


<script>
function myFunction(id) {
    var recognition = new (window.SpeechRecognition || 
        window.webkitSpeechRecognition || window.mozSpeechRecognition || 
        window.msSpeechRecognition)();
    recognition.lang = 'en-US';
    recognition.interimResults = false;
    recognition.maxAlternatives = 5;
    recognition.start();
    recognition.onresult = function(event) {    
         document.getElementById(id).value =(event.results[0][0].transcript);
    };
}
</script>