Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
            
                    
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,所以它是on-topic,用于堆栈溢出。
                        
                        2年前关闭。
                    
                
        

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title> speech synthesizer</title>
  </head>
  <body>
    <div class="voiceinator">
      <h1> My Speech Synthesizer </h1>

      <select id="voices" name="voice">
        <option value="">Select a voice</option>
      </select>

    <label for="rate">Rate:</label>
    <input type="range" name="rate" value="1" min="0" max="3" step="0.1">

    <label for="pitch">Pitch:</label>
    <input type="range" name="pitch" min="0" max="2" step="0.1">

    <textarea name="text"> Hello there! </textarea>
    <button type="button" id="stop"> Stop! </button>
    <button type="button" id="speak"> Speak </button>
    </div>
 <script type="text/javascript">

  const msg = new SpeechSynthesisUtterance();
  let voices = [];
  var voicesDropdown = document.querySelector('[name="voices"]');
  const options = document.querySelector('[name="range"], [name="text"]'); // this selects the rate control bar, pitch bar and text area
  const speakButton = document.querySelector('#speak');
  const stopButton = document.querySelector('#stop');
  msg.text = document.querySelector('[name="text"]').value;

  function populateVoices()
  {
    voices = this.getVoices();

    for( var i=0 ; i<voices.length ; i++ ){
      var opt = voices[i];
      var el = document.createElement("option");
      el.textContent = opt;
      el.value = opt;
      voicesDropdown.appendChild(el);
    }

  }
  //when speechSynthesis loads , voiceschanged event occurs and populateVoices function is fired
  speechSynthesis.addEventListener('voiceschanged', populateVoices);
 </script>
  </body>
</html>


这是我遇到的错误---如何解决?


  SPEECH SYNTHESIZER.html:45未捕获的TypeError:无法读取null的属性'appendChild'
      在SpeechSynthesis.populateVoices(SPEECH SYNTHESIZER.html:45)


还请告诉我如何将两个值附加到el.textContent?例如。我希望它显示voices[i].namevoices[i].lang

最佳答案

name上的<select>voice而不是voices。但是更简单,更有效地通过ID获得该元素

更改:

var voicesDropdown = document.querySelector('[name="voices"]');




var voicesDropdown = document.querySelector('#voices');

10-08 06:24