不知道为什么这不起作用...我正在尝试编写一个函数,但无法在单击按钮时得到任何响应,这对我来说毫无意义。
index.html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body>
<form class="input">
<h1 class="title"> Find A Pet Near You! </h1>
<label for="zip" id="hello">Zip</label>
<input type="text" name="zip" id="zip">
<button type="submit" id="submitZip" onclick="test()"> Submit </button>
</form>
</body>
<script src='script.js'></script>
</html>
脚本.js
function test() {
document.getElementById("submitZip").addEventListener("click", function(event){
// event.preventDefault()
// var url = 'https://api.petfinder.com/pet.getRandom';
var zip = document.getElementById('zip').value; // this line gets the zip code from the form entry
var test = document.getElementById('hello'); // this line clears the form after the user submits
this.innerText = "Loading..."; // this line changes the button text to loading
console.log("TEST");
});
}
我只是想在点击按钮时检测任何生命迹象......
您不需要在
addEventListener
函数内添加额外的监听器 (test
),因为您已经指定 test
来处理按钮的点击。
可能的解决方案1.
如果您的 HTML 代码需要保持不变,您的 JS 代码需要:
function test() {
// event.preventDefault()
// var url = 'https://api.petfinder.com/pet.getRandom';
var zip = document.getElementById('zip').value; // this line gets the zip code from the form entry
var test = document.getElementById('hello'); // this line clears the form after the user submits
// this.innerText = "Loading..."; // this line changes the button text to loading
console.log("TEST");
}
这将打印
TEST
.
可能的解决方案2.
如果您从 HTML 中删除
onclick
属性,您的 JS 代码可以是:
function test() {
// event.preventDefault()
// var url = 'https://api.petfinder.com/pet.getRandom';
var zip = document.getElementById('zip').value; // this line gets the zip code from the form entry
var test = document.getElementById('hello'); // this line clears the form after the user submits
// this.innerText = "Loading..."; // this line changes the button text to loading
console.log("TEST");
}
test();
或
document.getElementById("submitZip").addEventListener("click", function(event) {
// event.preventDefault()
// var url = 'https://api.petfinder.com/pet.getRandom';
var zip = document.getElementById('zip').value; // this line gets the zip code from the form entry
var test = document.getElementById('hello'); // this line clears the form after the user submits
this.innerText = "Loading..."; // this line changes the button text to loading
console.log("TEST");
});
注意:我已经留下了你写的所有评论。