JavaScript面向对象编程循环创建按钮时模板变量未生效问题
问题根因
你代码中使用的${}是JavaScript模板字符串的插值语法,该语法仅在**反引号()**包裹的字符串中生效,你当前使用单引号(')包裹HTML字符串,所以${this.playerNumber}`会被识别为普通文本,不会被解析为变量值。
修复方案
方案1:替换为模板字符串(兼容ES6+环境)
仅需修改newButton函数中字符串的包裹符号为反引号即可:
function newButton() { // 原单引号替换为反引号 return `<button id="${this.playerNumber}"></button>`; }
方案2:普通字符串拼接(兼容所有浏览器版本)
如果需要兼容不支持ES6模板字符串的老旧浏览器,改用加号拼接变量即可:
function newButton() { return '<button id="' + this.playerNumber + '"></button>'; }
方案3:直接使用DOM API创建元素(更推荐)
拼接HTML字符串存在XSS注入风险,直接创建DOM元素属性赋值更安全可控,可直接修改Player构造函数逻辑,无需单独写newButton方法:
function Player(playerNumber, timeout, sec) { this.playerNumber = playerNumber; this.timeout = timeout; this.sec = sec; this.div = document.createElement("div"); // 直接创建按钮并设置属性 const btn = document.createElement("button"); btn.id = this.playerNumber; this.div.appendChild(btn); }
内容的提问来源于stack exchange,提问作者djspatule
相关产品推荐
相关产品推荐

