简体   繁体   English

解析 HTML5 数据属性到 document.querySelector

[英]Parsing HTML5 data-attribute to document.querySelector

I have three HTML buttons with ids and classes.我有三个带有 id 和类的 HTML 按钮。 Two of them also hold data attributes.其中两个还持有数据属性。

The data attributes are for the element they should change the style display property for.数据属性用于它们应该更改样式显示属性的元素。

The basic idea is to show or hide paragraph elements.基本思想是显示或隐藏段落元素。 I am trying to reduce repetitive code by using querySelectors and for loops instead of having multiple event listeners.我试图通过使用 querySelectors 和 for 循环而不是使用多个事件侦听器来减少重复代码。 I am stuck at writing the function that starts on line 31 of the codepen.我一直在编写从 codepen 的第 31 行开始的函数。 I have tried: document.querySelector(classbtns[i].getAttribute('data-value')).style.display = "inline";我试过: document.querySelector(classbtns[i].getAttribute('data-value')).style.display = "inline"; and I am getting: TypeError: document.querySelector(...) is null我得到:TypeError: document.querySelector(...) is null

I have retained and commented out earlier code-blocks to help give you an idea of what I am trying to do.我保留并注释掉了早期的代码块,以帮助您了解我正在尝试做什么。

Please see my code and link to the codepen below:请查看我的代码并链接到下面的代码笔:

html: 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: css:

 #toy-pictures-latest.panel{
    display: inline;
}

#toy-pictures-greatest.panel{
        display: inline;
}

js: 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);

codepen代码笔

I found two issues:我发现了两个问题:

  1. In HTML, data-value tag for button "btngreatest" is missing end quote.在 HTML 中,按钮“btngreatest”的数据值标记缺少结束引号。

    <button type="button" id="btngreatest" data-value="toy-pictures-greatest class="buttons"> <button type="button" id="btngreatest" data-value="toy-pictures-greatest class="buttons">

  2. Since you want to select panels by ID, you should prefix with '#'由于要按 ID 选择面板,因此应以“#”为前缀

    document.querySelector('#'+ classbtns[i].getAttribute('data-value')).style.display = "inline"; document.querySelector('#'+ classbtns[i].getAttribute('data-value')).style.display = "inline";

When selecting an element by Id with document.querySelector you need to preface with "#" so that would be:当使用 document.querySelector 通过 Id 选择元素时,您需要以“#”开头,以便:

document.querySelector('#' + classbtns[i].getAttribute('data-value')).style.display = "inline";
      });

But then you might as well just use但是那么你不妨使用

document.getElementById(classbtns[i].getAttribute('data-value')).style.display = "inline";

Just as an additive to the solutions already it may be worth taking into consideration the good old MDN on getting the data attribute:作为已经解决方案的补充,可能值得考虑在获取数据属性时使用的旧 MDN:

[...], but the standard defines a simpler way: a DOMStringmap you can read out via a dataset property. [...],但标准定义了一种更简单的方法:可以通过数据集属性读取的 DOMStringmap。 https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

I personally would also go for the target of of the event.我个人也会去寻找活动的目标。 Something like:就像是:

const attachListener = btn => btn.addEventListener('click', (e) => document.getElementById(e.target.dataset.value).style.display = 'inline';

clsBtns.forEach(attachListener);

Here is a more current and simplified clean approach by using forEach method and targeting the actual element we have clicked on using event.target method这是使用forEach方法并使用event.target方法定位我们单击的实际元素的更当前和简化的清洁方法

Event.target will ensure you are targeting the correct element to get its data-value - This approach is better if you have alot of buttons and nested inside each other. Event.target将确保您定位正确的元素以获取其data-value - 如果您有很多按钮并且相互嵌套,则这种方法会更好

You can also use newly dataset approach as well instead of using the getAtribute method您也可以使用新的dataset方法而不是使用getAtribute方法

Using data.set使用数据

 document.querySelector("#" + e.target.dataset.value).style.display = "inline";

Live Demo:现场演示:

 function clearall() { var panels = document.querySelectorAll('.panel') panels.forEach(function(el) { el.style.display = "none"; }); } const classbtns = document.querySelectorAll(".buttons"); classbtns.forEach(function(btn) { btn.addEventListener("click", function(e) { document.querySelector("#" + e.target.getAttribute('data-value')).style.display = "inline"; }) }) //clear al; document.getElementById('clear-btn').addEventListener("click", clearall);
 #toy-pictures-latest.panel { display: none; } #toy-pictures-greatest.panel { display: none; }
 <p id="toy-pictures-latest" class="panel">Latest Toy Pictures</p><br> <p id="toy-pictures-greatest" class="panel">Greatest Toy Pictures</p> <br> 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> <button type="button" id="clear-btn">Clear</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM