gpt4 book ai didi

javascript - 如何解析以下代码中的 "cannot read property appendChild of null"?

转载 作者:行者123 更新时间:2023-11-28 17:53:25 24 4
gpt4 key购买 nike

<!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 Uncaught TypeError: Cannot read property 'appendChild' of null at 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');

关于javascript - 如何解析以下代码中的 "cannot read property appendChild of null"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44971770/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com