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

MVC应用同一JS文件实现两类用户功能方案咨询(无jQuery)

同应用多权限JS功能适配方案

你原本计划的动态注释切换代码的方案不推荐,实际生产环境下维护成本极高,更优的实现是同一份代码内置多套权限逻辑,运行时根据当前用户权限自动匹配对应执行方法,完全不需要手动修改代码注释。

以下是你要求的场景示例:

1. index.html 代码

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>权限适配示例</title>
</head>
<body>
  <button id="addBtn">添加新行</button>
  <div id="lineContainer"></div>
  <script src="main.js"></script>
</body>
</html>

2. main.js 代码

// 模拟从后端接口获取当前用户权限,实际项目中替换为真实接口返回值
// 权限枚举:'restricted' 为受限用户A,'unrestricted' 为非受限用户B
const currentUserPermission = 'restricted' 

// 非受限用户B的添加方法:无行数限制
function addLine() {
  const container = document.getElementById('lineContainer')
  const newLine = document.createElement('p')
  newLine.textContent = `这是第${container.children.length + 1}行内容`
  container.appendChild(newLine)
}

// 受限用户A的添加方法:最多添加5行
function restrictedAddLine() {
  const container = document.getElementById('lineContainer')
  if (container.children.length >= 5) {
    alert('您的权限最多只能添加5行内容')
    return
  }
  const newLine = document.createElement('p')
  newLine.textContent = `这是第${container.children.length + 1}行内容(受限用户)`
  container.appendChild(newLine)
}

// 根据权限绑定对应执行方法
const finalAddLine = currentUserPermission === 'unrestricted' ? addLine : restrictedAddLine

// 绑定按钮点击事件
document.getElementById('addBtn').addEventListener('click', finalAddLine)

方案优势

  • 所有逻辑都在同一份代码中,不需要做任何注释切换操作,部署后自动根据用户权限生效
  • 可扩展性强,后续如果新增更多权限等级,只需要新增对应方法,修改权限判断逻辑即可,原有业务调用代码不需要改动
  • 可以配合后端做权限校验,避免前端被篡改绕过限制(如果需要更高安全性,建议后端同时对操作次数做校验)

内容的提问来源于stack exchange,提问作者SIMBIOSIS surl

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 15:36:03