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

onclick按钮绑定JS随机句子生成函数运行失效问题求助

代码问题修复说明

两处核心错误

  • 语法错误:createMessage 函数的字符串拼接逻辑缺了加号,selectArr(locationArr) 和末尾的 "!" 之间没有拼接符,直接导致脚本报错无法运行
  • 逻辑错误:init 函数仅将生成的句子输出到控制台,没有设置返回值,所以点击按钮调用init时拿到的是undefined,页面无法正常展示内容

修复后代码

JS 代码

const personArr = ["Father Burgundy", "Constable Grey"];
const locationArr = ["the sauna", "the larder"];

const selectArr = (array) => {
  return array[Math.floor(Math.random()*array.length)];
}

const createMessage = () => {
  // 补全缺失的字符串拼接加号
  const message = "It was " + selectArr(personArr) + " in " + selectArr(locationArr) + "!";
  return message;
};

const init = () => {
  const message = createMessage();
  console.log(message);
  // 新增返回值,供页面赋值使用
  return message;
};

init();

function demo() {
  document.getElementById("output").innerHTML = init();
}

HTML 代码

原HTML逻辑无需修改,可直接使用:

<button id="btn" onclick="demo()">Click here!</button>
<p id="output"></p>

内容的提问来源于stack exchange,提问作者Samuel Villajos

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 18:15:05