JavaScript中如何让setAttribute的属性值引用变量?
在JavaScript中使用setAttribute时引用变量的方法
这问题其实很常见,你现在的代码里直接把n写在字符串里,JavaScript只会把它当成普通文本,不会去引用你定义的const n = '40px'这个变量。咱们可以用两种常用方法解决:
方法1:使用ES6模板字符串(推荐)
模板字符串是ES6引入的语法,用反引号()包裹字符串,变量用${变量名}`的形式插入,写法简洁又直观:
const main = document.querySelector('main'); const n = '40px'; const div = document.createElement('div'); div.setAttribute('class', 'grid'); main.appendChild(div); // 用模板字符串插入变量n div.setAttribute('style', `background-color: #f9f9f9; width: ${n}; height: ${n}`);
这种方式可读性很高,尤其当你需要插入多个变量时,比字符串拼接清爽多了。
方法2:传统字符串拼接
如果需要兼容不支持ES6的老旧浏览器,可以用+号把字符串和变量拼接起来:
const main = document.querySelector('main'); const n = '40px'; const div = document.createElement('div'); div.setAttribute('class', 'grid'); main.appendChild(div); // 字符串拼接变量n div.setAttribute('style', 'background-color: #f9f9f9; width: ' + n + '; height: ' + n);
补充:关于数字转带px的字符串
你提到后续要处理用户输入的数字转成xxxpx的字符串,其实很简单:假设用户输入的是数字(比如40),直接用模板字符串或者字符串拼接就能搞定:
// 假设userInput是用户输入的数字,比如40 const userInput = 40; const n = `${userInput}px`; // 结果是"40px" // 或者用拼接 const n = userInput + 'px';
这样不管用户输入的是数字类型还是字符串类型的数字,都能转换成带px单位的字符串。
内容的提问来源于stack exchange,提问作者user7217977
相关产品推荐
相关产品推荐

