![](/img/trans.png)
[英]Vanilla Javascript - How to loop through just elements in the DOM using querySelectorAll('*')
[英]Vanilla javascript: How to access DOM elements properties through a function parameter?
我对 Javascript 很陌生(对一般编程也是如此)。 我正在尝试制作一个 function ,它将接受一个参数(DOM 元素的名称)来访问其 DOM 属性。
例如,我预先创建了多个 DOM 元素:
const aGatherPlants = document.createElement('p');
aGatherPlants.className = 'gather-plants btn btn-medium btn-dark mrgn-b';
aGatherPlants.appendChild(document.createTextNode(`Plants [${costGatherPlants}]`));
aGatherPlants.style.display = 'none';
aGatheringTab.appendChild(aGatherPlants);
const aGatherWood = document.createElement('p');
aGatherWood.className = 'gather-wood btn btn-medium btn-dark mrgn-b';
aGatherWood.appendChild(document.createTextNode(`Wood [${costGatherWood}]`));
aGatherWood.style.display = 'none';
aGatheringTab.appendChild(aGatherWood);
我的目标是在 function 中访问这些元素的属性,例如element.style
、 element.appendChild
、 element.addEventListeners
等。
function functionName(property){
property.style.display = 'none';
}
functionName('aGatherPlants');
显然,它不起作用,并且浏览器控制台正在记录cannot access property.style of undefined
。
我想制作一个 function 来访问所有创建的 DOM 元素,而不必对每个元素进行硬编码。
任何人都可以在这里帮助新手吗? 如果您需要更多信息,请告诉我。
我可以看到你在 function 中传递了一个字符串而不是你想要的变量,请记住,当你在 ' ' 或 " " 之间放置一些东西时,你是在说 "这个值是一个字符串类型值",所以以后要注意这一点.
function functionName(property){
property.style.display = 'none';
}
//Here you are passing a string as paremeter
//but you want to pass the const aGatherPlants
functionName('aGatherPlants');
//So you need to do this instead
functionName(aGatherPlants);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.