当我在不同的城市打字并且我的代码无效时,我正在尝试更改背景。它只显示最后一个城市。当我输入不同的城市时,它不会重置并更改背景。继承我的代码。
$( document ).ready(function() {
$('#rugby').submit(function(e) {
e.preventDefault()
})
$('#submit-btn').click(function() {
$("#rugby").get(0).reset();
var city = $('#city-type').val();
``if (city == 'New York' || 'NYC' || 'NY') {
$('body').css('background-image', 'url("../dewaynehw5/images/nyc.jpg")')
}
if (city == 'San Francisco' || 'SF' || 'Bay Area') {
$('body').css('background-image', 'url("../dewaynehw5/images/sf.jpg")')
}
if (city == 'Los Angeles' || 'LA' || 'LAX') {
$('body').css('background-image', 'url("../dewaynehw5/images/la.jpg")')
}
if (city == 'Austin' || 'ATX') {
$('body').css('background-image', 'url("../dewaynehw5/images/austin.jpg")')
}
if (city == 'Sydney' || 'Syd') {
$('body').css('background-image', 'url("../dewaynehw5/images/sydney.jpg")')
}
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="Your description goes here">
<meta name="keywords" content="one, two, three">
<title>City Background</title>
<!-- external CSS link -->
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<header>
<div class="title">
<h1>CitiPix</h1>
<p>Your Cities, Your Pix</p>
</div>
</header>
<div class="container">
<form id="rugby">
<input type="text" id="city-type" placeholder="Enter a city name...">
<input type="submit" value="Update" id="submit-btn">
</form>
</div>
<script src='http://codepen.io/assets/libs/fullpage/jquery.js'></script>
<script src="js/main.js"></script>
</body>
</html>
答案 0 :(得分:0)
我在http://jsfiddle.net/m7xxkdz6/2/创建了一个小提琴,它应该演示您希望创建的功能。我使用CSS背景颜色而不是图像,并以纽约和旧金山为例。
$('#submit').click(function() {
// Get the input value and set it to lowercase. This way it doesn't matter how the user
// enters it into the input box, we'll always be dealing with the same data format
var inputValue = $('#input').val().toLowerCase();
// Cache the background element
var background = $('#background-element');
// Use a switch statement to match the input value and update the css
switch (inputValue) {
case 'new york' :
case 'nyc' :
background.css('background-color', 'green');
break;
case 'san fsfrancisco' :
case 'sf' :
background.css('background-color', 'pink');
break;
}
})
答案 1 :(得分:0)
只需在事件结束时重置表单..因为你在表单捕获值之前重置了表单..在你的代码中它每次都会将其清空
$( document ).ready(function() {
$('#rugby').submit(function(e) {
e.preventDefault()
var city = $.trim($('#city-type').val());
if(){
}.......
$("#rugby").get(0).reset(); // <<<< reset here
});
});
或在捕获值后使用它
var city = $.trim($('#city-type').val());
$("#rugby").get(0).reset();
你也可以用以下函数替换函数的结尾:
city.val('');
一旦函数运行,它将用空字符串替换所选城市。