Как я могу получить мои результаты для отображения в ряд? - PullRequest
0 голосов
/ 04 октября 2019

$(document).ready(function() {
  $("#submitForecast").click(function() {
    return getForecast();
  });
});

function getForecast() {
  var city = $("#city").val();
  var days = $("#days").val();

  if (city != '' && days != '') {

    $.ajax({
      url: 'http://api.openweathermap.org/data/2.5/forecast/daily?q=' + city + "&units=metric" + "&cnt=" + days + "&APPID=c10bb3bd22f90d636baa008b1529ee25",
      type: "GET",
      dataType: "jsonp",
      success: function(data) {
        var table = '';
        var header = '<h2 style="font-weight:bold; font-size:30px; margin-top:20px;">Weather forecast for ' + data.city.name + ', ' + data.city.country + '</h2>'
        for (var i = 0; i < data.list.length; i++) {
          table += "<tr>";
          table += "<td><img src='http://openweathermap.org/img/w/" + data.list[i].weather[0].icon + ".png'></td>";
          table += "<td>" + data.list[i].weather[0].main + "</td>";
          table += "<td>" + data.list[i].weather[0].description + "</td>";
          table += "<td>" + data.list[i].temp.morn + "&deg;C</td>";
          table += "<td>" + data.list[i].temp.night + "&deg;C</td>";
          table += "<td>" + data.list[i].temp.min + "&deg;C</td>";
          table += "<td>" + data.list[i].temp.max + "&deg;C</td>";
          table += "<td>" + data.list[i].pressure + "hpa</td>";
          table += "<td>" + data.list[i].humidity + "%</td>";
          table += "<td>" + data.list[i].speed + "m/s</td>";
          table += "<td>" + data.list[i].deg + "&deg;</td>";
          table += "</tr>";
        }

        $("#forecastWeather").html(table);
        $("#header").html(header);

        $("#city").val('');
        $("#days").val('')
      }
    });

  } else {
    $("#error").html("<div class='alert alert-danger' id='errorCity'><a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a>City field cannot be empty</div>");
  }
}
body {
    font-family: 'Tangerine', serif;
    background-color: #ffffff;
    font-size: 20px;
    margin: 0;
    padding: 0;
}

#nav_bar {
    margin-bottom: 0px;
    padding: 0;
    background-color: white;
    border: none;
}

.weather {
    color: #4aa1f3 !important;
    font-size: 25px;
    font-weight: 600;
}

#nav_list > li > a {
    color: #4aa1f3 !important;
    font-weight: 500;
}

#logo {
    max-height: 42px;
    margin-right: 8px;
    display: inline-block;
    margin-top: -15px;
}

#headRow {
    background: url(images/bg.jpg) no-repeat;
    background-size: cover;
    width: 100%;
    height: 450px;
    margin-top: 0px;
    margin-left: 0px;
}

#colHeadText1 {
    color: white;
    padding-top: 30px;
    font-size: 45px;
}

#colHeadText2 {
    color: white;
    padding-top: 20px;
    padding-bottom: 30px;
    font-size: 50px;
}

ul#list_item {
    color: white;
    font-size: 35px;
    text-align: center;
}

#cityDiv {
    width: 60%;
    margin: auto;
    text-align: center;
}

input[type='text'] {
    height: 40px;
    font-size: 20px;
}

#submitCity {
    height: 40px;
    font-weight: bold;
}

#errorCity {
    width: 50%;
    margin: auto;
    text-align: center;
}

.footer {
    background-color: #4aa1f3;
    width: 100%;
    height: 80px;
    margin-top: 10px;
    bottom: 0;
}

#showWeather {
    width: 60%;
    margin: auto;
    background-color: #4aa1f3;
    color: white;
    border-radius: 25px;

}

table {
    color: #333333;
    font-family: Helvetical, Arial, sans-serif;
}

th {
    background: #4aa1f3;
    font-weight: bold;
    max-width: 500px;
    margin-left: auto;
    margin-right: auto;

}

td {
    background: #FAFAFA;
    text-align: center;
    max-width: 500px;
    margin-left: auto;
    margin-right: auto;

}

#welcome-paragraph {
    font-size: 20px;
    font-weight: normal;
    padding: 12px 25px 40px 25px;
    letter-spacing: 0.5px;
}

#rowDiv {
    margin: auto;
    width: 100%;
    font-size: 18px;
    align-items: center;
    height:50px;
    list-style: none;
    max-width: 1500x;
    margin-left: auto;
    margin-right: auto;
    padding-left: 80px;
    padding-right: 80px;
    justify-content: space-around;
}

#colDesc h3 {
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 20px;
    text-transform: uppercase;
}

#colDesc {
    border: 1px solid #e7e7e7;
    margin: 0 auto;
    height: auto;
}

.info-icon {
    text-align: center;
}

.info-icon i {
    font-size: 60px;
    margin-top: 10px;
    color: #4aa1f3;
}

.typed-cursor {
    opacity: 1;
    -webkit-animation: blink 0.7s infinite;
    -moz-animation: blink 0.7s infinite;
    animation: blink 0.7s infinite;
}
@keyframes blink {
    0% { opacity:1; }
    50% { opacity:0; }
    100% { opacity:1; }
}
@-webkit-keyframes blink {
    0% { opacity:1; }
    50% { opacity:0; }
    100% { opacity:1; }
}
@-moz-keyframes blink {
    0% { opacity:1; }
    50% { opacity:0; }
    100% { opacity:1; }
}
    
.logo {
    font-family: "DM Sans", sans-serif;
    text-transform: uppercase;
    letter-spacing: 2px;
    font-size: 13px;
  }

  .header {
    height: 50px;
  }
  
  .navbar {
    background-color:rgba(247, 95, 95, 0.897);
    position: fixed;
    width: 100%;
  }
  
  .navbar-container {
    align-items: center;
    height:50px;
    display:flex;
    list-style: none;
    max-width: 1500px;
    margin-left: auto;
    margin-right: auto;
    padding-left: 20px;
    padding-right: 20px;
    justify-content: space-between;
 
  }
  
  a {
    text-decoration: none; 
    color: #252525;
  }
  
  .menu li a {
  }

  .menu > li {
      margin-left: 20px;
      text-decoration: none;
    }
  
  .menu {
    display: flex;
    flex-direction: row-reverse;
    justify-content: space-between;
    align-items: center;
    list-style:none;
    text-decoration: none; 
  }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Weather App - Forecast</title>
    
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    
    <link rel="stylesheet" href="style.css">
    
</head>
<body>
        <header class="headers">
                <nav class="navbars">
        
                    <div class="navbar-container">
                        <div class="logo">Mike Peavy</div>
                        <ul class="menu">
                            <li><a href="#bio">Bio</a></li>
                            <li><a href="#quiz">Portfolio</a></li>
                            <li><a href="https://github.com/Mike4141" target="_blank"> Github</a></li>
                        </ul>
                    </div>
                </nav>
            </header>

</nav> 

<div class="jumbotron" style="margin-bottom:0px; background-color:#4aa1f3; color:white;">
        <h2 class="text-center" style="font-size:40px; font-weight:600;">Get Weather Forecast</h2>
    </div>
    
    <div class="container" style="height:1350px;">
        <div class="row" >
            <div class="col-md-12" style="margin-bottom:10px;">
                <h3 class="text-center text-primary">Enter City Name</h3>
                <span id="error" class="text-center"></span>
            </div>
            
            <div class="row form-group form-inline" id="cityDiv">
               
                <input type="text" name="city" id="city" class="form-control" placeholder="Enter city name" >
                <input type="text" name="days" id="days" class="form-control" placeholder="Number: Min - 1 & Max - 16" >
                <button id="submitForecast" class="btn btn-primary">Search City</button>
            </div>
    
        </div>
        
        <div class= "change">
        <div class="row" style="margin-top:30px">
            <table class="table table-bordered">
               <div id="header"  class="text-center"></div>
               
                <thead>
                    <tr>
                            <th>Icon</th>
                            <th>Weather</th>
                            <th>Description</th>
                            <th>Morning Temperature</th>
                            <th>Night Temperature</th>
                            <th>Min. Temperature</th>
                            <th>Max. Temperature</th>
                            <th>Pressure</th>
                            <th>Humidity</th>
                            <th>Wind Speed</th>
                            <th>Wind Direction</th>
                    </tr>
                </thead>
                
                <tbody id="forecastWeather">
                    
                </tbody>
                
            </table>
        </div>
        
    </div>
    </div>
    <div class="footer">
        <div class="container">
            <div class="row text-center" style="padding-top:30px;">
                <p style="color:white">Copyright &copy; Weather App</p>
            </div>
        </div>
    </div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>        
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>   
     
<script src="forecast.js"></script>   
      
</body>
</html>

Я довольно новичок в веб-разработке, и я ищу кого-то опытного, чтобы помочь мне с моей проблемой. Я купил курс на Udemy по созданию приложения погоды. Я хочу внести в него изменения и сделать то, что, по моему мнению, будет выглядеть лучше. Как получить результаты, отображаемые в ряд, и при этом хорошо выглядеть на настольных ПК? Если мне нужно предоставить более подробное описание, пожалуйста, дайте мне знать, если вам нужно больше деталей.

Ответы [ 2 ]

0 голосов
/ 04 октября 2019

Если вы действительно хотите изучать веб-разработку, вам следует прекратить использовать jQuery и Bootstrap и сначала изучить основы Javascript и CSS. С одной стороны, jQuery находится на выходе (даже Bootstrap работает над его удалением в версии 5), а сама Bootstrap поддерживает плохой, несемантический стиль кодирования.

Не используйте встроенные стили. Все CSS принадлежат файлу CSS.

Не используйте идентификаторы , особенно для стилизации. Это нормально для определения элементов для подключения вашего JavaScript (и даже тогда могут быть лучшие альтернативы).

Существуют более эффективные способы построения HTML, чем просто конкатенация строк. По крайней мере, вы должны HTML-экранировать внешние значения, которые вы включаете в него. Посмотрите на этот ответ на другой вопрос для некоторых идей: Заголовки сообщений электронной почты не отображаются правильно, когда в заголовке указано «&», как исправить в JavaScript?

Наконец, не делайте 't использовать JSONP для запроса API. С CORS (который, похоже, поддерживает openweathermap) это избыточно и небезопасно.

0 голосов
/ 04 октября 2019

В этой статье предлагается несколько удобных табличных подходов для мобильных представлений: https://medium.com/appnroll-publication/5-practical-solutions-to-make-responsive-data-tables-ff031c48b122

Всегда старайтесь использовать "отзывчивость" с помощью CSS.

Что касается рабочего стола, можно использовать горизонтальную прокрутку,но это не каждый элегантный. Постарайтесь сохранить приличное количество столбцов (возможно, есть возможность удалить / добавить столбцы или получить дополнительную информацию, щелкнув элемент).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...