JavaScript 的 getElementById() 和 getElementsByName() 函数有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6351570/
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
What is the difference between JavaScript's getElementById() and getElementsByName() functions?
提问by KyleL
Other than the fact that my brief research tells me the latter will return a collection rather than a a single element with the ID passed.
除了我的简短研究告诉我后者将返回一个集合而不是一个传递了 ID 的单个元素这一事实之外。
Consider the following code:
考虑以下代码:
function validateAllFields()
{
var clientid = document.getElementById("clientid");
var programs = document.getElementById("programs");
var startmonth = document.getElementById("startmonth");
var startday = document.getElementById("startday");
var startyear = document.getElementById("startyear");
var completed = document.getElementsByName("completed");
var goals = document.getElementsByName("goals");
var errors = document.getElementById("errorMsg");
errors.innerHTML = "";
if(isNumeric(clientid, errors, "Please enter a valid client ID")){
if(madeSelection(programs, errors, "Please select a program from the drop-down list")){
if(madeSelection(startmonth, errors, "Please enter a month for the start date")){
if(madeSelection(startday, errors, "Please enter a day for the start date")){
if(madeSelection(startyear, errors, "Please enter a year for the start date")){
if(checked(completed, errors, "Please choose an option that indicate whether the client has completed the program")){
if(checked(goals, errors, "Please choose an option that indicate whether the client has met his/her goals.")){
window.alert("GOT IN TO RETURN TRUE");
return true;
}
}
}
}
}
}
}
return false;
}
</script>
The above code works perfectly after placing it in the onsubmit handler of the form. However, earlier, for the elements (programs, startmonth, startday, startyear) I was using getElementsByName(), the following happened:
将上面的代码放在表单的 onsubmit 处理程序中后,它可以完美运行。然而,早些时候,对于我使用 getElementsByName() 的元素(programs、startmonth、startday、startyear),发生了以下情况:
- The code seems to get to the second line of the if blocks "if(madeSelection(programs...." and it displayed the error msg via innerHTML for a brief second and
- Proceeded to submit the form AS IF the JS had indeed returned true. As you can tell, there is a popup alert right before returning true and the popup DID NOT show up at all.
- Bad data was submitted to my test database because the form had not been validated. (yet to write server-side validation with this form, but I will).
- 代码似乎到达 if 块“if(madeSelection(programs....”) 的第二行,它通过innerHTML 显示错误消息一秒钟,然后
- 继续提交表单,就像 JS 确实返回 true 一样。如您所知,在返回 true 之前有一个弹出警报,并且该弹出窗口根本没有出现。
- 由于表单未经验证,错误数据被提交到我的测试数据库。(尚未使用此表单编写服务器端验证,但我会)。
please assume the elements programs, startmonth, startday, and startyearare drop-down lists with the same id and name attributes.
请假设元素program、startmonth、startday和startyear是具有相同 id 和 name 属性的下拉列表。
Also, the madeSelection function is given as:
此外, madeSelection 函数给出如下:
function madeSelection(element, error, msg) {
if (element[0].value == "none" || element[0].valueOf == "none" || element[0].value == "") {
error.innerHTML = msg;
element.focus();
return false;
} else {
return true;
}
}
My code does work right now after I changed those elements to be using getElementById(), I was just wondering why getElementsByName presented such behavior.
在我将这些元素更改为使用 getElementById() 后,我的代码现在确实可以工作,我只是想知道为什么 getElementsByName 会呈现这种行为。
回答by deceze
<input type="text" name="foo" id="bar">
^^^^ ^^
getElementsByName
gets elements by their name
, getElementById
gets the element by its id
. There may be many elements on a page with the same name
(hence getElementsByName
always returns a list of elements), but there is (must) only be one element with a given id
(therefore getElementById
only returns a single element).
getElementsByName
通过他们得到的元素name
,getElementById
通过它获取元素id
。一个页面上可能有很多相同的元素name
(因此getElementsByName
总是返回一个元素列表),但是(必须)只有一个元素具有给定的id
(因此getElementById
只返回一个元素)。
回答by Guffa
The GetElementsByName
method returns an array, and when you tried to call element.focus()
you got an error because there is no focus
method on an array. When you get an error in the event handler it won't prevent the form from posting.
该GetElementsByName
方法返回一个数组,当您尝试调用element.focus()
时出现错误,因为focus
数组上没有方法。当您在事件处理程序中遇到错误时,它不会阻止表单发布。
If you use GetElementById
you should use element
to access the element, and if you use GetElementsByName
you should use element[0]
.
如果你使用GetElementById
你应该使用element
来访问元素,如果你使用GetElementsByName
你应该使用element[0]
.
回答by k_b
The name attribute is not designed to be unique, while the id attribute is.
name 属性不是唯一的,而 id 属性是。
<div name="nonUnique" />
<div id="unique" />
回答by David Edwards
To expand a little on the answers already provided, the nameattribute was provided early in the days of the browser DOM, to allow the contents of elements in forms to be submitted with reference to that name attribute, so that parameters could be passed to a CGI script at the server side. This dates from before the more modern ability to reference DOM elements for manipulation of such things as styles by JavaScript.
为了扩展已经提供的答案,在浏览器 DOM 时代的早期就提供了name属性,以允许参考该 name 属性提交表单中元素的内容,以便可以将参数传递给服务器端的 CGI 脚本。这可以追溯到更现代的引用 DOM 元素以通过 JavaScript 操作诸如样式之类的东西的能力之前。
When the DOM was expanded to allow said modern manipulations, the idattribute was added, so that individual elements could be manipulated at will. When you want to perform DOM manipulations, you select elements to be manipulated eithervia the idattribute, if you're only interested in manipulating a single DOM element, or via the classattribute (suitably set by yourself), if you want to manipulate several elements together in the same manner. In this latter case, you can set the classattribute to multiple values (name strings separated by spaces), so that you can, for example, designate elements to belong to more than one class, and perform manipulations accordingly. You can mix and match idand classattributes practically at will, provided you exercise some care to avoid name clashes.
当 DOM 被扩展以允许所述现代操作时,添加了id属性,以便可以随意操作单个元素。当你想要执行 DOM 操作时,你可以通过id属性选择要操作的元素,如果你只对操作单个 DOM 元素感兴趣,或者通过class属性(适合自己设置),如果你想操作几个元素以相同的方式组合在一起。在后一种情况下,您可以将class属性设置为多个值(名称字符串由空格分隔),例如,您可以指定元素属于多个类,并相应地执行操作。您可以混合搭配id和类属性实际上是随意的,前提是您要小心避免名称冲突。
So, for example, you could have five buttons on your web page, all set to:
因此,例如,您的网页上可以有五个按钮,全部设置为:
class="Set1"
类 =“Set1”
and change the style of all those buttons, first by using a statement such as:
并更改所有这些按钮的样式,首先使用如下语句:
myButtons = document.getElementsByClassName("Set1");
to obtain an array of Element objects corresponding to your buttons, then running the following loop:
获取与您的按钮对应的 Element 对象数组,然后运行以下循环:
for (i=0; i<myButtons.length; i++)
myButtons[i].style.color="#FF0000";
to change the colour of the text to red. One of those buttons could additionally have an id attribute set to "Special", and you could then do something such as:
将文本颜色更改为红色。其中一个按钮还可以将 id 属性设置为“特殊”,然后您可以执行以下操作:
ref = document.getElementById("Special");
ref.style.backgroundColor = "#FFFF00";
to set the background colour of that one button in the set to yellow, to signal that it's intended for a special function within the set.
将集合中那个按钮的背景颜色设置为黄色,以表示它用于集合中的特殊功能。
In short, use the nameattribute for form submissions, and the idand classattributes for referring to elements you intend to perform DOM manipulations upon, or attach event handlers to, etc.
简而言之,使用name属性进行表单提交,使用id和class属性来引用您打算对其执行 DOM 操作或附加事件处理程序等的元素。
回答by shas
The getElementById method can access only one element at a time, and that is the element with the ID that you specified. The getElementsByName method is different. It collects an array of elements that have the name that you specified. You access the individual elements using an index which starts at 0.
getElementById 方法一次只能访问一个元素,即具有您指定 ID 的元素。getElementsByName 方法是不同的。它收集具有您指定名称的元素数组。您可以使用从 0 开始的索引访问各个元素。
getElementById
getElementById
- It will get only one element for you.
- That element bears the ID that you specified inside the parentheses of getElementById().
- 它只会为您获取一个元素。
- 该元素带有您在 getElementById() 括号内指定的 ID。
getElementsByName
按名称获取元素
- It will get a collection of elements whose names are all the same.
- Each element is indexed with a number starting from 0 just like an array
- You specify which element you wish to access by putting its index number into the square brackets in getElementsByName's syntax below.
- 它将获得名称都相同的元素的集合。
- 每个元素都用一个从 0 开始的数字作为索引,就像数组一样
- 您可以通过将索引号放入下面 getElementsByName 语法中的方括号中来指定要访问的元素。
function test() {
var str = document.getElementById("a").value;
console.log(str);
var str1 = document.getElementsByName("a")[0].value;
console.log(str1);
var str2 = document.getElementsByName("a")[1].value;
console.log(str2);
}
<input type="text" id="a" value="aValue" />
<br>
<br>
<input type="text" name="a" value="bValue" />
<br>
<br>
<input type="text" name="a" value="cValue" />
<br>
<br>
<button onclick="test()">Click Here</button>
回答by Pantelis
In order for the form to not be submitted, return false needs to be returned (you said you used the onsubmit handler)
为了不提交表单,需要返回 return false (您说您使用了 onsubmit 处理程序)
in the second line of your code, because a selection is indeed returned by getElementsByName (it would work with .getElementsByName("test")[0] ) a js error is thrown. The rest of the code is not executed, therefore nothing is returned and the form by-passes the rest of the validation completely.
在代码的第二行中,因为 getElementsByName 确实返回了一个选择(它可以与 .getElementsByName("test")[0] 一起使用)抛出一个 js 错误。其余代码不会执行,因此不会返回任何内容,并且表单完全绕过了其余的验证。