【发布时间】:2019-03-17 21:17:06
【问题描述】:
我正在开发一个简单的 JS 项目,它从 API 调用数据并返回到页面。还有一个“重置”按钮,可以将 API 调用重置回基线。我无法弄清楚如何让元素重置。通常我会用 CSS 类来做,但是这一次,我将构建一个更大的分配,它将从用户 ID 调用 API。所以我想纯粹通过 JS/jQuery 来做这件事,而不使用表单元素。
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Weather Vain</title>
</head>
<h1> Weather 4 Ever </h1>
<body class = "change">
<p class="prompt">Type in a US city to get temperature data!</p>
<form class="pure-form">
<input type="text" class="pure-input-rounded">
<button type="submit" class="pure-button">Search</button>
<button type="submit" class="reset-button">Reset</button>
</form>
<p id="forecast"></p>
<p class="date"></p>
</body>
</html>
CSS
html, body {
background-color: #5CBF94;
font-weight: 100;
color: #FFF;
}
h1, h2, h3, h4, h5, h6, p {
text-align: center;
font-weight: 100;
width: 100%;
}
h1 {
font-size: 3em;
}
.prompt {
font-size: 1.2em;
margin-top: 4em;
}
form {
color: #000;
width: 290px;
margin: 0 auto;
}
.date {
position: absolute;
bottom: 0;
text-align: center;
}
img {
margin: 0 auto;
}
JS
console.log("Script loaded")
"use strict";
(function() {
$('.pure-button').click(function(e) {
e.preventDefault()
console.log("click noticed")
$.ajax({
url: "https://api.openweathermap.org/data/2.5/weather?q=" + $('.pure-input-rounded').val() + ",US&appid=6549863730776a52fadf3fe935d5eecc&units=Imperial",
type: "GET",
success: function(data){
var temp = data.main.temp
var sky = data.weather[0].description
$('#forecast').text("The current temperature in " + $('.pure-input-rounded').val() + " is " + temp + " degrees Fahrenheit. It is currently " + sky + "." )
}
})
})
(".reset-button").onclick.reset() //this is the part that I need to figure out.
})();
CodePen 链接:https://codepen.io/anfperez/pen/NJzPoE
谁能给我指点?
【问题讨论】:
-
呼叫重置?
$("form")[0].reset()或者使用重置按钮type="reset" -
你最好使用
$('.pure-form').submit(function(e) {,看我的回答如下 -
和
$('.pure-form').on('reset', function(e) {清除其他部分
标签: javascript jquery json onclick reset