简体   繁体   English

我怎样才能 select 在 javascript 中的 HTMLCollection 中的特定元素

[英]How can i select a specific element in a HTMLCollection in javascript

I have a div container with a certain number of div's created with a for loop inside of it.我有一个 div 容器,其中包含一定数量的 div,其中创建了一个 for 循环。 When i click one of these a divs, i need to make it change the colour.当我点击其中一个 div 时,我需要让它改变颜色。 My problem is can't figure out how to select an specific element with the addEventListener to change the color.我的问题是无法弄清楚如何使用 select addEventListener 更改颜色的特定元素。

<body>
    <div id="main-container"></div>
    <script src="script.js"></script>
</body>

const mainContainer = document.getElementById("main-container");
for (let i = 0; i <= 11; ++i) {
    const gridChildrens = document.createElement("div");
    gridChildrens.setAttribute("class", `gridChildrens`);
    const grids = document.querySelector('.gridChildrens')
    mainContainer.appendChild(gridChildrens);
}

For the moment, i figure out how to change the color of the firt or the last of the elements with a click listener, but not for the rest of the of the divs.目前,我弄清楚如何使用点击侦听器更改第一个或最后一个元素的颜色,但不是 div 的 rest。

For the moment, i figure out how to change the color of the firt or the last of the elements with a click listener, but not for the rest of the of the divs.目前,我弄清楚如何使用点击侦听器更改第一个或最后一个元素的颜色,但不是 div 的 rest。 I expect to click any of the divs and change the color.我希望单击任何 div 并更改颜色。

Try to add an event listener to each div created in the loop and then use 'this' to set your colour.尝试向循环中创建的每个 div 添加事件侦听器,然后使用“this”设置颜色。 Here's an example:这是一个例子:

const mainContainer = document.getElementById("main-container");
        for (let i = 0; i <= 11; ++i) {
            const gridChildrens = document.createElement("div");
            gridChildrens.setAttribute("class", `gridChildrens`);
            gridChildrens.addEventListener('click', function() {
                this.style.backgroundColor = 'red';
            });
            mainContainer.appendChild(gridChildrens);
        }

Code snippet sample :代码片段示例

 <html> <head> <style>.gridChildrens { width: 50px; height: 50px; background-color: blue; margin: 10px; } </style> </head> <body> <div id="main-container"></div> <script> const mainContainer = document.getElementById("main-container"); for (let i = 0; i <= 11; ++i) { const gridChildrens = document.createElement("div"); gridChildrens.setAttribute("class", `gridChildrens`); gridChildrens.addEventListener('click', function() { this.style.backgroundColor = 'red'; }); mainContainer.appendChild(gridChildrens); } </script> </body> </html>

To explicitly target an element the querySelector without click event (which will inspect the event.target ) you can use the nth-child or nth-of-type style css selector as below.要在没有click事件(将检查 event.target )的情况下显式定位querySelector元素,您可以使用nth-childnth-of-type样式 css 选择器,如下所示。

To identify an element based upon user click the event itself will expose the target property which will be the element that caused the event handler to fire.要根据用户单击来识别元素, event本身将公开target属性,该属性将是导致事件处理程序触发的元素。 The following uses a delegated event listener bound to the document itself which processes all click events if required but here responds only to those bound to the gridChildrens elements以下使用绑定到文档本身的delegated event listener器,它在需要时处理所有单击事件,但此处仅响应绑定到gridChildrens元素的事件

 const mainContainer = document.getElementById("main-container"); for (let i = 0; i <= 11; ++i) { const div = document.createElement("div"); div.setAttribute("class", `gridChildrens`); div.textContent=i; mainContainer.appendChild( div ); } document.querySelector('.gridChildrens:nth-of-type(4)').classList.add('banana') document.querySelector('.gridChildrens:nth-of-type(7)').classList.add('banana') document.querySelector('.gridChildrens:nth-of-type(10)').classList.add('banana') document.addEventListener('click',e=>{ if( e.target instanceof HTMLDivElement && e.target.classList.contains('gridChildrens') ){ e.target.classList.toggle('tomato') } })
 .gridChildrens{ width:50%; height:1rem; margin:0.25rem; }.banana{ background:yellow }.tomato{ background:tomato }
 <div id="main-container"></div>

This should give you a good idea of how to use addEventlistner .这应该让您很好地了解如何使用addEventlistner Basically, you can pass the event object whenever you make some event.基本上,只要你做一些事件,你就可以传递event object 。 That has all the information of the specific div that you are looking for, you can change anything with that.它包含您要查找的特定 div 的所有信息,您可以用它更改任何内容。 But remember to bind the elements with addEventlistner first.但是记得先用addEventlistner绑定元素。

 var containers= document.getElementsByClassName("container"); const changeColor = (e)=>{ if(e.target.style.background =="orange"){ e.target.style.background ="red" } else e.target.style.background ="orange"; } for(var i=0; i< containers.length; i++){ containers[i].addEventListener('click',function(e){ changeColor(e) } ); }
 .container{ height:50px; width:100px; background: #000; margin:10px 10px; border-radius:10px; cursor:pointer; }.holder{ display:flex; flex-wrap:wrap; }
 <div class="holder"> <div class="container"></div> <div class="container"></div> <div class="container"></div> <div class="container"></div> <div class="container"></div> </div>

There are several ways to do this.有几种方法可以做到这一点。 For example, you can add the same class to your divs inside the loop.例如,您可以将相同的 class 添加到循环内的 div。 Then you can access them via document.querySelectorAll('.class-name') .然后您可以通过document.querySelectorAll('.class-name')访问它们。 So smth like this:所以像这样:

[...document.querySelectorAll('.class-name')].forEach( el => {
  el.addEventListener('click', (e) => { changeColor(e); });
});

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

相关问题 如何将元素添加到 javascript 中的 HTMLCollection 中? - How to add an element into the HTMLCollection in javascript? JavaScript我如何遍历HTMLcollection中的每个当前和将来的元素? - JavaScript how do i iterate over every current and future element in a HTMLcollection? 如何<span>在使用 JavaScript 的链接的 HTMLCollection 内的文本中<a>使用 select 文本?</a></span> - How do I select text inside a <span> that is inside an HTMLCollection of links <a> using JavaScript? 如何获得循环 HTMLCollection 的子节点? - How can I get child of loop HTMLCollection? TypeScript或JS-如何选择元素及其所有子元素进入HTMLCollection? - TypeScript or JS- How to select an element and all its children into a HTMLCollection? 如何使用javascript选择此元素? - How can I select this element with javascript? 如何使用javascript检查HTMLCollection是否包含具有给定类名的元素? - How to check if an HTMLCollection contains an element with a given class name using javascript? 如何在HTMLCollection或Element上使Javascript Cals /构造函数可调用 - How to make Javascript calss/constructor callable on HTMLCollection or Element 如何在Javascript的SELECT元素中设置或选择一个选项 - How can I set or select an option in a SELECT element on Javascript 如何在JavaScript中检测HTMLCollection / NodeList? - How to detect HTMLCollection/NodeList in JavaScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM