简体   繁体   English

如何从元素数组中动态获取元素的值?

[英]How do I dynamically get the value of an element from an array of elements?

I have a form with 3 checkboxes.我有一个带有 3 个复选框的表单。 I'm trying to the value of whichever checkbox is clicked on.我正在尝试单击任何复选框的值。 I'm able to get the value of a hardcoded checkbox index (checkbox[0] for example), but I can't get the value of checkbox[i] with vanilla JS.我能够获得硬编码复选框索引的值(例如 checkbox[0]),但我无法使用 vanilla JS 获得 checkbox[i] 的值。

 document.addEventListener("DOMContentLoaded", function() { var checkboxes = document.getElementsByClassName('checkbox'); var listType = document.getElementById('ListType'); for (var i = 0; i < checkboxes.length; i++) { checkboxes[i].addEventListener('click', function() { var inputByIndex = checkboxes[0].value; //I can get the value of the first element, but I can't get the value of whichever checkbox is checked. checkbox[i] doesn't work. listType.classList.add(inputByIndex); var spanType = document.getElementById("type"); spanType.innerText = inputByIndex; }); } });
 input { margin: 20px; } #ListType.basiclist { color: red; } #ListType.accordionlist { color: blue; } #ListType.internalonly { color: pink; }
 <form id="ListTypes"> <label for "basicList"><input type="checkbox" id="basicList" class="checkbox" name="basicList" value="basiclist"/>Basic List</label> <label for "accordionList"><input type="checkbox" id="accordionList" class="checkbox" name="accordionList" value="accordionlist"/>Accordion List</label> <label for "internalOnly"><input type="checkbox" id="internalOnly" class="checkbox" name="internalOnly" value="internalonly" />Internal Use Only</label> </form> <div id="ListType"> List Type: <span id="type"></span> </div>

Fiddle小提琴

You can use event.currentTarget to access the element on which event has occurred.您可以使用event.currentTarget访问发生事件的元素。

The currentTarget read-only property of the Event interface identifies the current target for the event, as the event traverses the DOM.当事件遍历 DOM 时,Event 接口的 currentTarget 只读属性标识事件的当前目标。

 document.addEventListener("DOMContentLoaded", function() { var checkboxes = document.getElementsByClassName('checkbox'); var listType = document.getElementById('ListType'); for (var i = 0; i < checkboxes.length; i++) { checkboxes[i].addEventListener('click', function(event) { var inputByIndex = event.currentTarget.value; listType.classList.add(inputByIndex); var spanType = document.getElementById("type"); spanType.innerText = inputByIndex; }); } });
 input { margin: 20px; } #ListType.basiclist { color: red; } #ListType.accordionlist { color: blue; } #ListType.internalonly { color: pink; }
 <form id="ListTypes"> <label for "basicList"><input type="checkbox" id="basicList" class="checkbox" name="basicList" value="basiclist"/>Basic List</label> <label for "accordionList"><input type="checkbox" id="accordionList" class="checkbox" name="accordionList" value="accordionlist"/>Accordion List</label> <label for "internalOnly"><input type="checkbox" id="internalOnly" class="checkbox" name="internalOnly" value="internalonly" />Internal Use Only</label> </form> <div id="ListType"> List Type: <span id="type"></span> </div>

In the for loop, use let instead of var to make it work:for循环中,使用let而不是var使其工作:

 document.addEventListener("DOMContentLoaded", function() { var checkboxes = document.getElementsByClassName('checkbox'); var listType = document.getElementById('ListType'); for (let i = 0; i < checkboxes.length; i++) { checkboxes[i].addEventListener('click', function() { var inputByIndex = checkboxes[i].value; //I can get the value of the first element, but I can't get the value of whichever checkbox is checked. checkbox[i] doesn't work. listType.classList.add(inputByIndex); var spanType = document.getElementById("type"); spanType.innerText = inputByIndex; }); } });
 input { margin: 20px; } #ListType.basiclist { color: red; } #ListType.accordionlist { color: blue; } #ListType.internalonly { color: pink; }
 <form id="ListTypes"> <label for "basicList"><input type="checkbox" id="basicList" class="checkbox" name="basicList" value="basiclist"/>Basic List</label> <label for "accordionList"><input type="checkbox" id="accordionList" class="checkbox" name="accordionList" value="accordionlist"/>Accordion List</label> <label for "internalOnly"><input type="checkbox" id="internalOnly" class="checkbox" name="internalOnly" value="internalonly" />Internal Use Only</label> </form> <div id="ListType"> List Type: <span id="type"></span> </div>

Delegate代表

You need to think of the CSS for more than one listType color or use a set of radio buttons您需要为多个 listType 颜色考虑 CSS 或使用一组单选按钮

 document.addEventListener("DOMContentLoaded", function() { document.getElementById('ListTypes').addEventListener("click", function(e) { const tgt = e.target; if (tgt.type && tgt.type === 'checkbox') { const values = [...tgt.form.querySelectorAll("[type=checkbox]:checked")].map(chk => chk.value); document.getElementById("type").textContent = values.join(", ") document.getElementById("ListType").classList.add(...values); } }); });
 input { margin: 20px; } #ListType.basiclist { color: red; } #ListType.accordionlist { color: blue; } #ListType.internalonly { color: pink; }
 <form id="ListTypes"> <label for "basicList"><input type="checkbox" id="basicList" class="checkbox" name="basicList" value="basiclist"/>Basic List</label> <label for "accordionList"><input type="checkbox" id="accordionList" class="checkbox" name="accordionList" value="accordionlist"/>Accordion List</label> <label for "internalOnly"><input type="checkbox" id="internalOnly" class="checkbox" name="internalOnly" value="internalonly" />Internal Use Only</label> </form> <div id="ListType"> List Type: <span id="type"></span> </div>

the checkboxes list doesn't exist within the closure of the onclick funcion.onclick函数的关闭中不存在checkboxes列表。 Instead use this.value .而是使用this.value

JS fiddle JS小提琴

You just need to select them all using the method you would like (I used querySelectorAll & ) and do an iteration over them (I used forEach() ).您只需要使用您喜欢的方法(我使用querySelectorAll & )选择它们,并对它们进行迭代(我使用forEach() )。

This is the most simple function you can ever find.这是您能找到的最简单的功能。

 const checkboxes = document.querySelectorAll('input[type="checkbox"]'); checkboxes.forEach(singleCheckbox => { singleCheckbox.addEventListener('click', () => alert(singleCheckbox.id)) });
 <label for="first">First<input type="checkbox" id="first"/></label> <label for="second">Second<input type="checkbox" id="second"/></label> <label for="third">Third<input type="checkbox" id="third"/></label>

Just to make clear what was actually the problem with your code...只是为了弄清楚您的代码的实际问题是什么......

At the time you click handler will be fired the for loop will end its work and thus, the value of i will become exactly checkboxes.length , and of course, there is no checkbox with such an index, because the last of them has index (checkboxes.length - 1) .当您click处理程序时, for循环将结束其工作,因此, i的值将变为checkboxes.length ,当然,没有具有此类索引的复选框,因为它们中的最后一个具有索引(checkboxes.length - 1) So the reason is that the code inside of the handler is executed after for loop ends its work.所以原因是处理程序内部的代码是for循环结束工作执行的。

The solutions were already provided by other users.其他用户已经提供了这些解决方案。

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

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