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

JavaScript如何给变量/函数加参数 避免重复编写页面解锁触发代码

优化实现方案

核心修改逻辑

  1. 你之前写的var check(x,y)= pgUnlock.includes(x,y);属于语法错误,JS中函数声明不能这么写,且Array.includes()的参数顺序是反的:第一个参数是要查找的目标值,第二个是开始查找的索引位置,原用法无法正常匹配值
  2. 原有check变量是页面加载时一次性计算的静态值,后续pgUnlock更新后不会自动刷新,改为校验时动态判断更合理
  3. 给alertbox增加入参适配不同按钮的校验需求,同时用配置表统一管理按钮映射关系,完全消除重复代码

优化后完整代码

// 初始化解锁数组,索引0-4对应5个板块
const pgUnlock = [0,0,0,0,0];
const alertBtn = document.querySelector('替换为你的alertBtn实际选择器'); // 补全原代码缺失的alertBtn声明避免报错
const reBtn = document.querySelector('.rebtn');
// 请自行补全legBtn、godBtn、chgBtn、ch2Btn的DOM获取逻辑

// 按钮配置表:统一存储每个按钮对应的解锁索引、解锁后跳转地址
const btnConfig = [
  { btn: reBtn, unlockIndex: 0, targetUrl: './introPage.html' },
  { btn: legBtn, unlockIndex: 1, targetUrl: './legendPage.html' },
  { btn: godBtn, unlockIndex: 2, targetUrl: './godPage.html' },
  { btn: chgBtn, unlockIndex: 3, targetUrl: './chapter1.html' },
  { btn: ch2Btn, unlockIndex: 4, targetUrl: './chapter2.html' },
]

// 页面加载时批量设置已解锁按钮的跳转地址
btnConfig.forEach(item => {
  if (pgUnlock[item.unlockIndex] === 1) {
    item.btn.setAttribute('href', item.targetUrl);
  }
})

// 批量绑定点击事件,无需重复写5次onclick
btnConfig.forEach(item => {
  item.btn.onclick = () => {
    alertbox(item.unlockIndex);
  }
})

// 复用的校验函数,入参为当前按钮对应要校验的解锁位索引
function alertbox(unlockIndex) {
  if (pgUnlock[unlockIndex] !== 1) {
    alertBtn.classList.add("visalert");
  }
}

补充说明

  • 直接取pgUnlock[索引]判断状态的性能比遍历数组的includes更高,不需要单独声明5个check变量
  • 后续新增板块只需要在btnConfig里加一行配置即可,不需要新增校验逻辑
  • 如果你确实需要单独封装通用check函数,可以这样写:
    const checkUnlock = (targetValue, startIndex) => pgUnlock.includes(targetValue, startIndex);
    // 调用示例:checkUnlock(1, 0) 表示从索引0开始查找是否存在值为1的项
    

内容的提问来源于stack exchange,提问作者Iron Lemon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 22:18:04