【发布时间】:2020-09-13 05:41:38
【问题描述】:
我有三个带有 ID 和类的 HTML 按钮。其中两个还持有数据属性。
数据属性适用于它们应该更改其样式显示属性的元素。
基本思想是显示或隐藏段落元素。 我试图通过使用 querySelectors 和 for 循环而不是拥有多个事件侦听器来减少重复代码。 我一直在编写从 codepen 第 31 行开始的函数。我试过: document.querySelector(classbtns[i].getAttribute('data-value')).style.display = "inline"; 我得到: TypeError: document.querySelector(...) is null
我保留并注释掉了早期的代码块,以帮助您了解我正在尝试做什么。
请查看我的代码并链接到下面的代码笔:
html:
<p id="toy-pictures-latest" class="panel">Latest Toy Pictures</p><br>
<p id="toy-pictures-greatest" class="panel">Greatest Toy Pictures</p>
Toy Pictures
<button type="button" id="btnlatest" data-value="toy-pictures-latest" class="buttons">Latest</button>
<button type="button" id="btngreatest" data-value="toy-pictures-greatest class="buttons">Greatest</button></details></li>
<button type="button" id="clear-btn">Clear</button>
css:
#toy-pictures-latest.panel{
display: inline;
}
#toy-pictures-greatest.panel{
display: inline;
}
js:
/*function fgreatest() {
document.getElementById('toy-pictures-greatest').style.display = "inline";
}*/
//The following function clears the p elements in class "panel" by changing the display value in css
function clearall()
{
var panels = document.querySelectorAll('.panel'), i;
console.log("exe");
for (i = 0; i < panels.length; ++i) {
panels[i].style.display = "none";
}
}
//This is the previous version of the querySelector.
//It required a new function for each <p> element id
/*const classbtns = document.querySelectorAll(".buttons");
for (let i = 0; i < classbtns.length; i++) {
classbtns[i].addEventListener("click", fgreatest);
}*/
//This is the attempt to grab the name of the element
//from the html data value property and change the css //style display to inline
const classbtns = document.querySelectorAll(".buttons");
for (let i = 0; i < classbtns.length; i++) {
classbtns[i].addEventListener("click", function() {
document.querySelector(classbtns[i].getAttribute('data-value')).style.display = "inline";
});
}
document.getElementById('clear-btn').addEventListener("click", clearall);
【问题讨论】:
标签: javascript html dom queryselector