如何通过字符串变量中的名称获取全局声明的变量?
Hey there! Let's break down how to get those global variables using the string you're generating from the button's data-field attribute.
方法1:利用全局变量挂载在window对象上的特性
Since your variables (htmlArea, cssArea, jsArea) are declared in the global scope, they automatically become properties of the browser's window object. You can access them using bracket notation with your place string:
function copyTextfield() { const place = this.dataset.field+"Area"; const targetArea = window[place]; // 这就拿到了对应的全局变量 // 举个复制操作的例子,你可以继续写: targetArea.select(); document.execCommand("copy"); }
This works because any variable declared in the global scope (with const, let, or var) gets attached to the window object, and bracket notation lets you access object properties using string values.
方法2:更推荐的方式——用统一对象管理变量
While the window approach works, it's cleaner and safer to avoid polluting the global namespace. Instead, store your area elements in a single object:
// 把所有代码区域元素统一存到一个对象里 const codeAreas = { htmlArea: document.querySelector(".htmlCopy"), cssArea: document.querySelector(".cssCopy"), jsArea: document.querySelector(".jsCopy") }; const copyButtons = document.querySelectorAll(".copyBtn"); copyButtons.forEach(el => el.addEventListener("click", copyTextfield)); function copyTextfield() { const place = this.dataset.field+"Area"; const targetArea = codeAreas[place]; // 从对象中直接获取对应元素 }
This keeps your variables organized, reduces global clutter, and makes it easier to maintain if you add more code areas later.
避坑提醒:别用eval()
You might have thought of using eval(place) to get the variable, but this is not recommended. eval() executes arbitrary code, which can introduce security risks (especially if user input is involved) and hurt performance. Stick to the above methods instead.
内容的提问来源于stack exchange,提问作者Konrad Ryczko

