Выдает ошибку в коде

439
03 июля 2018, 02:00

Сегодня я запустил код и мне выдали такую ошибку :

Uncaught TypeError: Cannot read property 'time' of null

И не только св-во time,но и св-во name и body.

Я не могу понять , что происходит. Вчера вроде все хорошо было . Помогите кто может. Заранее благодарю.

Код:

let comments = [];
loadComments();
document.getElementById('comment-add').onclick = function(){
let commentName = document.getElementById('comment-name');
let commentBody = document.getElementById('comment-body');
let comment = {
    name : commentName.value,
    body : commentBody.value,
    time : Math.floor(Date.now() / 1000)
}
commentName.value = '';
commentBody.value = '';
comments.unshift(comment);
saveComments();
showComments();
}
function saveComments(){
    localStorage.setItem('comments', JSON.stringify(comments));
}
function loadComments(){
    if (localStorage.getItem('comments')) comments = 
        JSON.parse(localStorage.getItem('comments'));
        showComments();
}
function showComments (){
    let commentField = document.getElementById('comment-field');
    let out = '';
    comments.forEach(function(item){
        out += `<p class="text-right small"><em>${timeConverter(item.time)} 
   </em></p>`;
    out += `<p class="alert alert-primary" role="alert">${item.name} </p>`;
        out += `<p class="alert alert-success" role="alert">${item.body} 
   </p>`;
        });
        commentField.innerHTML = out;
    }
function timeConverter(UNIX_timestamp){
    var a = new Date(UNIX_timestamp * 1000);
    var months = 
['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    var year = a.getFullYear();
    var month = months[a.getMonth()];
    var date = a.getDate();
    var hour = a.getHours();
    var min = a.getMinutes();
    var sec = a.getSeconds();
    var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + 
':' + sec ;
    return time;
  }

Если вам понадобится верстка , то пишите .

Для тех , кому нужен HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chat</title>
          <link rel="stylesheet" 
 href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<script 
src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-lg-12">
            <h2 class="text-center">
                Comment
            </h2>
        </div>
        <div class="col-lg-6">
            <div id="comment-field"></div>
        </div>
        <div class="col-lg-6">
                <form>
                        <div class="form-group">
                          <label for="comment-name">Name:</label>
                          <input type="text" class="form-control" id="comment-name"  placeholder="Enter your name">
                        </div>
                        <div class="form-group">
                          <label for="comment-body">Comment:</label>
                          <textarea type="text" class="form-control" id="comment-body" placeholder="comment"></textarea>
                        </div>
                        <div class="form-group form-check text-right">
                                <button type="submit" id="comment-add" class="btn btn-primary">add Comment</button>
                        </div>
                      </form>
        </div>
    </div>
</div>


<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
<script src="script.js"></script>

Answer 1

А в каком браузере? И можно ваш html пожалуйста. В Chrome работает.

let comments = []; 
//loadComments(); 
 
document.getElementById('comment-add').onclick = function(){ 
let commentName = document.getElementById('comment-name'); 
let commentBody = document.getElementById('comment-body'); 
 
let comment = { 
    name : commentName.value, 
    body : commentBody.value, 
    time : Math.floor(Date.now() / 1000) 
} 
 
commentName.value = ''; 
commentBody.value = ''; 
 
comments.unshift(comment); 
//saveComments(); 
showComments(); 
} 
 
//function saveComments(){ 
//    localStorage.setItem('comments', JSON.stringify(comments)); 
//} 
 
//function loadComments(){ 
//    if (localStorage.getItem('comments')) comments =  
//        JSON.parse(localStorage.getItem('comments')); 
//        showComments(); 
//} 
 
function showComments (){ 
    let commentField = document.getElementById('comment-field'); 
    let out = ''; 
    comments.forEach(function(item){ 
        out += `<p class="text-right small"><em>${timeConverter(item.time)}  
   </em></p>`; 
    out += `<p class="alert alert-primary" role="alert">${item.name} </p>`; 
        out += `<p class="alert alert-success" role="alert">${item.body}  
   </p>`; 
        }); 
        commentField.innerHTML = out; 
    } 
 
function timeConverter(UNIX_timestamp){ 
    var a = new Date(UNIX_timestamp * 1000); 
    var months =  
['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']; 
    var year = a.getFullYear(); 
    var month = months[a.getMonth()]; 
    var date = a.getDate(); 
    var hour = a.getHours(); 
    var min = a.getMinutes(); 
    var sec = a.getSeconds(); 
    var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min +  
':' + sec ; 
    return time; 
  }
<input id="comment-name">comment-name</input> 
<input id="comment-body">comment-body</input> 
<button id="comment-add">Click me</button> 
<div id="comment-field"></div>

READ ALSO
Организация вывода файлов, gulp

Организация вывода файлов, gulp

Есть такой gulpfile, я его только начал делать, установил плагины

161