在浏览器上打开html时Javascript文件不起作用

时间:2019-05-06 09:10:02

标签: javascript html css

我有一个带有链接的CSS和javascript文件的html文件。该html应该像一个通讯录,可以在其中添加联系人,按名称搜索联系人并显示通讯录中的所有联系人。我从Codepen页面获得了代码,但是当我尝试在文件中使用它时,它不起作用,我也不知道为什么。下面是带有原始代码的codepen文件,我的代码将显示在代码段中。

documentation

persons = [
    person = {
      firstName: "Maria",
      lastName: "Fernanda",
      age: "mf@desk.com",
      phone: "917697967"
    },
  ];
  
  document.getElementById('search_button').addEventListener('click', searchPerson);
  document.getElementById('add_button').addEventListener('click', addPerson);
  document.getElementById('show_all').addEventListener('click', showAllPersons);

  function searchPerson() {
    var input = document.getElementById("search").value.toLowerCase();
    var result = document.getElementById('result');
  
    for (var i = 0; i < persons.length; i++) {
  
      if (input === persons[i].firstName.toLowerCase() || input === persons[i].lastName.toLowerCase()) {
        result.innerHTML = '<h4>I found this:</h4>' + persons[i].firstName + ' ' +
          persons[i].lastName + ' </br>' + persons[i].age + ' </br>' + persons[i].phone;
        return persons[i];
  
      } else if (!isNaN(input)) {
        result.innerHTML = 'Tem de inserir um nome';
      } else {
        result.innerHTML = 'Nenhum contacto encontrado';
      }
    }
  }
  
  function Person(first, last, age, phone) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.phone = phone;
  }
  
  function titleCase(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
  }
  
  function addPerson() {
    var firstName = titleCase(document.getElementById("name").value);
    var lastName = titleCase(document.getElementById("lastname").value);
    var age = document.getElementById("age").value;
    var phone = document.getElementById("phone").value;
  
    var newPerson = new Person(firstName, lastName, age, phone);
    persons.push(newPerson);
  
    if (newPerson.firstName != undefined) {
      alert(newPerson.firstName + ' added');
    } else {
      alert('No person added');
    }
    
    showAllPersons();
  }
  
  function showAllPersons() {
    var i;
    var l;
    var showButton = document.getElementById('show_all');
    var list = document.getElementById('all_list');
    
    while (list.firstChild) {
      list.removeChild(list.firstChild);
    }
    
    
    for (var l = 0; l < persons.length; l++) {
      var node = document.createElement("LI");
      list.appendChild(node);
      node.innerHTML =
        '<p><b>Nome Completo:</b> ' + persons[l].firstName +' ' + persons[l].lastName + '</p>' +
        '<p><b>Email:</b> ' + persons[l].age + '</p>' +
        '<p><b>Telemovel:</b> ' + persons[l].phone + '</p>'
  
      for (var key in person) {
        var value = person[key];
      }
    }
    showButton.disabled = true;
  }
html {
  box-sizing: border-box;
}

*, *::after, *::before {
  box-sizing: inherit;
}

form {
  padding: 20px 0 40px;
}
form .field {
  padding: 10px 0;
  margin: 5px 0;
  display: inline-block;
  width: 100%;
}
form .field label {
  float: left;
  display: block;
  margin-right: 2.3576520234%;
  width: 40.291369653%;
  padding: 5px 10px;
}
form .field label:last-child {
  margin-right: 0;
}
form .field input {
  float: left;
  display: block;
  margin-right: 2.3576520234%;
  width: 57.3509783236%;
  padding: 5px 10px;
}
form .field input:last-child {
  margin-right: 0;
}

.container {
  max-width: 1200px;
  margin-left: auto;
  margin-right: auto;
  text-align: center;
}
.container::after {
  clear: both;
  content: "";
  display: block;
}

.search_person {
  float: left;
  display: block;
  margin-right: 2.3576520234%;
  width: 48.8211739883%;
}
.search_person:last-child {
  margin-right: 0;
}

.add_person {
  float: left;
  display: block;
  margin-right: 2.3576520234%;
  width: 48.8211739883%;
}
.add_person:last-child {
  margin-right: 0;
}

.all_persons {
  float: left;
  display: block;
  margin-right: 2.3576520234%;
  width: 31.7615653177%;
  margin-left: 34.1192173411%;
}
.all_persons:last-child {
  margin-right: 0;
}
.all_persons #all_list {
  list-style-type: none;
  margin: 20px 0;
  padding: 0;
}
.all_persons #all_list li {
  margin: 0 0 30px;
  text-align: left;
}
<html>
    <head>
        <title>Desk+ - Grupo 36</title>
        <link rel="stylesheet" type="text/css" href="ab.css">
        <script src="ab.js"></script>
        </head>
<body>
<div class="container">
    <h1>Contactos</h1>
    
    <div class="all_persons">
      <button id="show_all" type="button">Mostrar todos</button>
      <ul id="all_list">
      </ul>
    </div>
    
    <div class="search_person">
      <h3>Insira um nome</h3>
      <input type="text" id="search">
      <button id="search_button" type="button">Procurar</button>
      <p id="result"></p>
    </div>
  
   <div class="add_person">
     <h3>Adicionar contacto</h3>
      <form action="" method="post">
        <div class="field">
          <label for="firstname">Primeiro Nome: </label>
          <input type="text" id="name">
        </div>
        <div class="field">
          <label for="lastname">Último Nome: </label>
          <input type="text" id="lastname">
        </div>
        <div class="field">
          <label for="age">Email: </label>
          <input type="text" id="age">
        </div>
        <div class="field">
          <label for="phone">Phone: </label>
          <input type="number" id="phone">
        </div>
        <button id="add_button" type="button">Add</button>
      </form>
    </div>
  </div>
</body>
</html>

显然,代码可以在代码段中运行,但是当我在浏览器中创建html页面时,它无法正常工作,所以您能帮我吗?

1 个答案:

答案 0 :(得分:2)

如评论中所述,将脚本移到body标签的末尾将解决您的问题,但是,更好的方法是将脚本的直接调用部分(而不是函数定义)括起来在load事件监听器中。不论您放置脚本的位置如何,仅在加载页面中的所有元素之后才会触发该事件。

window.addEventListener('load', (event) => {
    console.log('page is fully loaded');
});

您的脚本应如下所示。

window.addEventListener('load', (event) => {
    document.getElementById('search_button').addEventListener('click', searchPerson);
    document.getElementById('add_button').addEventListener('click', addPerson);
    document.getElementById('show_all').addEventListener('click', showAllPersons);
});