我有这个HTML文件......
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>simple II</title>
</head>
<body>
<div id="results"><!-- Results are displayed here -->
<form method="post" name="start" target="_blank">
<p>Enter thing1: <input type="text" id="thing1" name="thing1" size="10" /></p>
<p>Enter thing2: <input type="text" id="thing2" name="thing2" size="10" /></p>
<p>Enter thing3: <input type="text" id="thing3" name="thing3" size="10" /></p>
<p>Check thing4: <input type="checkbox" id="thing4" name="thing4" value=1>
<input type="hidden" id="state" name="state" value="one" /></p>
</form>
<button id='clickme' name='clickme'>Click me</button>
</div>
<script src="simple2.js?0000000000002"></script>
</body>
</html>
...和这个javascript源文件......
document.querySelector("#results button").addEventListener("click", function(e) {
e.preventDefault();
var inputs = document.querySelectorAll("input");
var params;
var amp = "";
for( var i = 0; i < inputs.length; i++ ) {
var input = inputs[i];
var name = input.getAttribute(name);
var value = input.getAttribute(value);
params += amp + name + "=" + value;
amp = "&";
}
alert( params );
});
...当我填写表格并点击按钮时,我得到了这个结果:
Everthing为“null”:( 我在这做错了什么?
答案 0 :(得分:4)
您需要引用getAttribute
中的值var name = input.getAttribute('name');
var value = input.getAttribute('value');
虽然name
和value
是dom元素的原生,但您也可以使用
var name = input.name;
var value = input.value;
或者,这可以使用https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
完成document.querySelector("#clickme").addEventListener("click", function() {
alert([].reduce.call(document.querySelectorAll("input"),function(pre,cur){
return (pre == "" ? pre : pre+"&") + cur.name + "=" + cur.value;
},""));
});
答案 1 :(得分:0)
使用现代 JS:
document.querySelectorAll('.className').forEach(elem => console.log(elem.getAttribute('attribute-you-want')));