我有一个简单的表单,我想输入内容并存储它。当按钮在窗体内时,addEventListener()方法将不起作用。这是代码,首先是html,然后是JavaScript
<!DOCTYPE html>
<html>
<head></head>
<body>
<form>
<h1>Enter words to display </h1>
<fieldset>
<input type="text" id="wordName" name="wordName">
</fieldset>
<button id="addWord">Add word</button>
</form>
<script type="text/javascript" src="ch2_ex2.js"></script>
</body>
</html>
使用Javascript:
var wordInput = document.getElementById("wordName");
var addWord = document.getElementById("addWord");
addWord.addEventListener("click", fillArray);
function fillArray() {
console.log("do something");
}
我发现fillArray()方法没有被调用。为什么是这样?当我将按钮放在<body>
正下方但不在<form>
答案 0 :(得分:1)
这里是demo
试试这个:
document.addEventListener("DOMContentLoaded", function(event) {
var btn = document.getElementById('addWord');
btn.addEventListener('click', fillArray, false);
function fillArray(e) {
e.preventDefault();
alert('foo');
}
});
}
答案 1 :(得分:0)
您还可以将按钮更改为表单提交按钮,并阻止默认的浏览器行为。请参阅下面的演示。
var wordInput = document.getElementById("wordName");
var form_el = document.getElementById("myForm");
form_el.addEventListener("submit", function(evt) {
evt.preventDefault();
fillArray();
});
function fillArray() {
console.log("do something with "+ wordInput.value);
var out = document.getElementById("out");
out.innerHTML = "you've entered: " + wordInput.value;
}
&#13;
<form id="myForm">
<h1>Enter words to display </h1>
<fieldset>
<input type="text" id="wordName" name="wordName"/>
</fieldset>
<input type="submit" value="Add word"/>
</form>
<div id="out"></div>
&#13;