Javascript 类型错误:document.getElementById(...) 为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27581667/
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
Javascript TypeError: document.getElementById(...) is null
提问by Robert-Dan
Here is my html
code:
这是我的html
代码:
<form name="searchForm" action="javascript:;" method="post" />
<p>
<label for="search">Search the site:</label>
<input type="text" id="search" name="search" value="xhr" />
<input type="submit" value="Search" />
</p>
</form>
In the header, I included my JavaScript file with the following specific code:
在标题中,我包含了我的 JavaScript 文件,其中包含以下特定代码:
window.onload = function () {
getValues = function (id) {
var i, values = [], form = document.getElementById(id);
for (i = 0; i < form.length ;i++) {
values.push( form.elements[i].value );
}
return values;
}
}
I've tried to access the function with console.log(getValues("searchForm") );
but instead in my Firefox
console, I received the following error: TypeError: form is null
.
我试图访问该函数,console.log(getValues("searchForm") );
但在我的Firefox
控制台中,我收到以下错误:TypeError: form is null
.
Can anyone suggest why this doesn't work?
谁能建议为什么这不起作用?
回答by Amit Joki
You're using name
attribute's value, not id
. So either you need to change name
to id
or use
您正在使用name
属性的值,而不是id
. 因此,您需要更改name
为id
或使用
form = document.getElementsByName(id)[0];
Also note that if you use the above code, it will return NodeList
so you need to use index to get the desired element.
另请注意,如果您使用上面的代码,它将返回,NodeList
因此您需要使用 index 来获取所需的元素。
回答by code_monk
To get all the values of a form:
要获取表单的所有值:
"use strict";
var findValuesIn = function(form) {
var fields = form.querySelectorAll('input,textarea,select'),
values = {},
i;
for (i in fields) {
values[ fields[i].name ] = fields[i].value;
}
return values;
}
document.getElementById('obtainValues').addEventListener('click',function(){
var ourForm = document.getElementById('f');
var vals = findValuesIn(ourForm);
// debug
document.getElementById('debug').innerHTML = JSON.stringify(vals);
});
input, select, textarea {
float: left;
}
button {
float: left;
clear: both;
margin: 1em;
}
label {
float: left;
clear: left;
width: 10em;
}
output {
display: block;
clear: both;
margin: 1em;
padding: .5em;
border: 1px solid gray;
background-color: #eee;
}
<form name="f" id="f">
<label for="name">Name</label>
<input type="text" name="name" />
<label for="search">Search</label>
<input type="search" name="search" />
<label for="favouriteColour">Favourite Colour</label>
<select name="favouriteColour">
<option>red</option>
<option>blue</option>
<option>yellow</option>
</select>
<button id="obtainValues">obtain values</button>
</form>
<output id="debug" form="f"></output>