javascript GetElementsByName 带有类似名称的数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18074868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:39:27  来源:igfitidea点击:

GetElementsByName with array like name

javascriptforeachgetelementsbyname

提问by AndreaBogazzi

i often use this notation when i name my controls in order to get an array in POST or GET.

我经常在命名控件时使用这种表示法,以便在 POST 或 GET 中获取数组。

<input name="color[1]" type="text" />
<input name="color[2]" type="text" />
<input name="color[3]" type="text" />

so in my scripts i can do

所以在我的脚本中我可以做到

<?php $data=$_GET["color"]; 
for each ($color as $key=>$value) {
   doSomething();
} ?>

Often happens that i need to get those id back in javascript , but i cannot get them , so i often add an ID to each element in html like that

经常发生我需要在 javascript 中取回那些 id,但我无法得到它们,所以我经常像这样为 html 中的每个元素添加一个 ID

<input name="color[3]" id="color_3" type="text" />

so that i can use document.getElementsById('color_3')

这样我就可以使用 document.getElementsById('color_3')

Instead i would like to find way to use document.getElementsByName(color[3])... but i cannot really get it to work.

相反,我想找到使用 document.getElementsByName(color[3]) 的方法......但我无法真正让它工作。

Any help?

有什么帮助吗?

采纳答案by Prasath K

<input name="color[3]" id="color_3" type="text" />

var element = document.getElementsByName("color[3]");

alert(element[0].id);

It works fine .. The thing you should have in your mind is Return type is an array of elements not a single element

它工作正常..你应该记住的是返回类型是一个元素数组而不是单个元素

回答by CodingIntrigue

If you want allof the color inputs, you can use querySelectorAllinstead to query for the name attribute:

如果你想要所有的颜色输入,你可以使用querySelectorAll来查询 name 属性:

document.querySelectorAll("input[name^='color[']")

This looks through the document for all inputtags whose name attribute starts with color[. Hereis a fiddle for this.

这会在文档中查找inputname 属性以 开头的所有标签color[是一个小提琴。

If you only want color[3], you can use:

如果你只想要color[3],你可以使用:

var color3 = document.getElementsByName("color[3]");
console.log(color3[0]);