以下HTML在第一次单击时在控制台中显示空数组:
<!DOCTYPE html>
<html>
<head>
<script>
function test(){
console.log(window.speechSynthesis.getVoices())
}
</script>
</head>
<body>
<a href="#" onclick="test()">Test</a>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
在第二次单击中,您将获得预期的列表.
如果添加onload事件来调用此函数(<body onload="test()">),则可以在第一次单击时获得正确的结果.请注意,第一次调用onload仍然无法正常工作.它在页面加载时返回空,但后续工作.
问题:
由于它可能是测试版中的错误,我放弃了"为什么"的问题.
现在,问题是您是否要window.speechSynthesis在页面加载时访问:
speechSynthesis在页面加载时确保它会加载?背景和测试:
我正在测试Web Speech API中的新功能,然后我在我的代码中遇到了这个问题:
<script type="text/javascript">
$(document).ready(function(){
// Browser support messages. (You might need Chrome 33.0 Beta)
if (!('speechSynthesis' in window)) {
alert("You don't have speechSynthesis");
}
var voices = window.speechSynthesis.getVoices();
console.log(voices) // []
$("#test").on('click', function(){
var voices = window.speechSynthesis.getVoices();
console.log(voices); // …Run Code Online (Sandbox Code Playgroud)