You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript文本转语音按钮触发无响应,无法朗读段落求助

问题解决:按钮触发段落朗读无响应

核心问题

你按钮的onclick事件里传的words.value是无效的——页面里根本没有名为words的元素,自然拿不到内容,导致朗读函数接收到空值,所以没有任何响应。

修改后的完整代码

<body>
  <h1>Web page heading</h1>
  <p id="speakit">Welcome to my web page</p>
  <button onclick="speak(document.getElementById('speakit').textContent)">Say it</button>

  <script>
    function speak(words) {
      const speech = new SpeechSynthesisUtterance();

      // 设置要朗读的文本
      speech.text = words;

      // 获取语音合成实例
      const speechSynthesis = window.speechSynthesis;

      // 开始朗读
      speechSynthesis.speak(speech);
    }
  </script>
</body>

关键改动说明

  • 把按钮的onclick参数改成document.getElementById('speakit').textContent,直接获取指定段落的文本内容传递给朗读函数
  • 修正了变量名拼写错误:speach改成speech(不影响功能但符合规范)

额外优化建议

你也可以把获取元素的逻辑放到函数内部,让HTML结构更简洁:

<body>
  <h1>Web page heading</h1>
  <p id="speakit">Welcome to my web page</p>
  <button onclick="speak()">Say it</button>

  <script>
    function speak() {
      const speech = new SpeechSynthesisUtterance();
      // 直接在函数内获取段落文本
      speech.text = document.getElementById('speakit').textContent;
      const speechSynthesis = window.speechSynthesis;
      speechSynthesis.speak(speech);
    }
  </script>
</body>

内容的提问来源于stack exchange,提问作者Alan Jarvis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 23:12:46