html JS.Templates.Contact manager / EdX的W3Cx JavaScript入门课程/
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html JS.Templates.Contact manager / EdX的W3Cx JavaScript入门课程/相关的知识,希望对你有一定的参考价值。
/************************************************/
/******************Styles************************/
/************************************************/
#warningMessage {
background-color: rgb(255, 102, 102, 0.5);
font-weight: bold;
}
fieldset {
border-color: #9999ff;
box-shadow:0 8px 16px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
}
legend {
font-weight: bold;
/* text-shadow: 2px 2px 5px #6666ff; */
}
label:hover {
cursor: pointer;
}
button {
border-radius: 10px;
border: none;
background-color: #6666ff;
box-shadow:0 8px 16px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
font-weight: bold;
}
button:hover {
background-color: #9999ff;
cursor: pointer;
}
table {
box-shadow:0 8px 16px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
}
table:hover {
cursor: pointer;
}
th#columnForEmails + th:hover {
cursor: auto;
}
th {
background-color: #9999ff;
}
tr:nth-child(even) {
background-color: #ccffee;
}
tr:nth-child(odd) {
background-color: #f0f5f5;
}
h2 {
text-shadow: 2px 2px 5px #6666ff;
}
.container {
background-color: #ffc966;
}
fieldset {
background-color: #b3e7ff;
}
body {
background-color: #ffe6e6;
}
/************************************************/
/******************Layouts************************/
/************************************************/
* {
margin: 0px;
padding: 0px;
box-sizing: border-box;
}
html, body {
width: 100%;
}
div {
width: 100%;
}
div.container {
display: flex;
flex-wrap: wrap;
justify-content: space-evenly;
align-items: stretch;
margin: 0px 0px 20px 0px;
padding: 15px 0px;
}
@media only screen and (min-width: 768px) {
.form-container, .search-container {
max-width: 490px;
}
}
fieldset {
display: inline-block;
padding: 10px;
border-radius: 10px;
}
fieldset label {
width: auto;
float: left;
}
input {
float:right;
}
input:invalid {
background-color:pink;
}
input:valid {
background-color:lightgreen;
}
h2 {
text-align: center;
}
p {
display: inline-block;
}
div#contacts {
overflow-x: auto;
}
table {
margin-top: 20px;
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
table, p {
position: relative;
left: 50%;
transform: translateX(-50%);
}
td, th {
height: 40px;
}
label {
display: inline-block;
width: 100%;
height: 100%;
vertical-align: middle;
padding: 6px;
}
label:after {
content:"";
display: inline-block;
width: 1px solid transparent;
height: 100%;
vertical-align: middle;
}
td > input {
width: 100%;
}
button {
height: 30px;
padding: 6px;
margin-top: 15px;
}
#dArrName, #uArrName, #dArrEmail, #uArrEmail {
position: absolute;
}
#warningMessage {
position: absolute;
display: none;
padding: 6px;
margin-top: -15px; /*the container have 15px padding*/
}
.hidden {
display: none;
}
.shown {
display: block;
}
window.onload= init;
// The contact manager as a global variable
let cm;
var searchInput;
function init() {
// create an instance of the contact manager
cm = new ContactManager();
cm.addTestData();
cm.printContactsToConsole();
// Display contacts in a table
// Pass the id of the HTML element that will contain the table
cm.displayContactsAsATable("contacts");
// cm.sortedBy = "nameAlphabetical";
cm.save();
searchInput = document.getElementById("search");
searchInput.addEventListener("input", search);
}
function search(){
loadList();
var input = searchInput.value.toLowerCase();
if(input == ""){
loadList();
}
for(i=0; i<cm.listOfContacts.length; i++){
var currentContact = cm.listOfContacts[i];
var name = currentContact.name;
var partOfName = name.slice(0, input.length).toLowerCase();
if(partOfName !== input){
cm.remove(currentContact);
i--;
}
}
cm.displayContactsAsATable("contacts");
}
function formSubmitted() {
// Get the values from input fields
let name = document.querySelector("#name");
let email = document.querySelector("#email");
let newContact = new Contact(name.value, email.value);
cm.add(newContact);
// Empty the input fields
name.value = "";
email.value = "";
// refresh the html table
cm.displayContactsAsATable("contacts");
displayWarningMessage();
// do not let your browser submit the form using HTTP
return false;
}
function emptyList() {
cm.empty();
displayWarningMessage();
cm.displayContactsAsATable("contacts");
}
function loadList() {
cm.load();
cm.displayContactsAsATable("contacts");
}
class Contact {
constructor(name, email) {
this.name = name;
this.email = email;
}
}
class ContactManager {
constructor() {
// when we build the contact manager, it
// has an empty list of contacts
this.listOfContacts = [];
this.sortedBy = "";
}
addTestData() {
var c1 = new Contact("Jimi Hendrix", "jimi@rip.com");
var c2 = new Contact("Robert Fripp", "robert.fripp@kingcrimson.com");
var c3 = new Contact("Angus Young", "angus@acdc.com");
var c4 = new Contact("Arnold Schwarzenneger", "T2@terminator.com");
this.add(c1);
this.add(c2);
this.add(c3);
this.add(c4);
}
// Will erase all contacts
empty() {
this.listOfContacts = [];
}
add(contact) {
this.listOfContacts.push(contact);
}
remove(contact) {
for(let i = 0; i < this.listOfContacts.length; i++) {
var c = this.listOfContacts[i];
if(c.email === contact.email) {
// remove the contact at index i
this.listOfContacts.splice(i, 1);
// stop/exit the loop
break;
}
}
}
sort(){
switch(this.sortedBy){
case "nameAlphabetical":
this.listOfContacts.sort(ContactManager.compareByName);
break;
case "nameReverse":
this.listOfContacts.sort(ContactManager.compareByName);
this.listOfContacts.reverse();
break;
case "emailAlphabetical":
this.listOfContacts.sort(ContactManager.compareByEmail);
break;
case "emailReverse":
this.listOfContacts.sort(ContactManager.compareByEmail);
this.listOfContacts.reverse();
break;
default:
this.listOfContacts.sort(ContactManager.compareByName);
this.sortedBy = "nameAlphabetical"
}
}
// class method for comparing two contacts by name
static compareByName(c1, c2) {
// JavaScript has builtin capabilities for comparing strings
// in alphabetical order
if (c1.name.toLowerCase() < c2.name.toLowerCase())
return -1;
if (c1.name.toLowerCase() > c2.name.toLowerCase())
return 1;
return 0;
}
static compareByEmail(c1, c2) {
// JavaScript has builtin capabilities for comparing strings
// in alphabetical order
if (c1.email.toLowerCase() < c2.email.toLowerCase())
return -1;
if (c1.email.toLowerCase() > c2.email.toLowerCase())
return 1;
return 0;
}
printContactsToConsole() {
this.listOfContacts.forEach(function(c) {
console.log(c.name);
});
}
load() {
if(localStorage.contacts !== undefined) {
// the array of contacts is savec in JSON, let's convert
// it back to a reak JavaScript object.
this.listOfContacts = JSON.parse(localStorage.contacts);
}
}
save() {
// We can only save strings in local Storage. So, let's convert
// ou array of contacts to JSON
localStorage.contacts = JSON.stringify(this.listOfContacts);
}
displayContactsAsATable(idOfContainer) {
// empty the container that contains the results
let container = document.querySelector("#" + idOfContainer);
container.innerHTML = "";
if(this.listOfContacts.length === 0) {
container.innerHTML = "<p>No contacts to display!</p>";
// stop the execution of this method
return;
}
var table = document.createElement("table");
table.setAttribute("id", "table");
var thead = table.insertRow().innerHTML = "<th id='columnForNames'>Name" +
"<span id='dArrName' class='arrow'> ↓</span>" +
"<span id='uArrName' class='arrow'> ↑</span></th>" +
"<th id='columnForEmails'>Email" +
"<span id='dArrEmail' class='arrow'> ↓</span>" +
"<span id='uArrEmail' class='arrow'> ↑</span>" +
"</th><th>Del</th>";
var rowIndex = 0;
this.sort();
// iterate on the array of users
this.listOfContacts.forEach(function(currentContact) {
// creates a row
ContactManager.createRow(rowIndex, table, currentContact);
rowIndex++;
});
// adds the table to the div
container.appendChild(table);
showHideArrow();
addEventListenerForTrashbinIcon();
addEventListenerToTableHead();
addEventListenerToTableCells();
}
static createRow(rowIndex, table, currentContact){
var row = table.insertRow();
row.setAttribute("id", rowIndex);
ContactManager.createCellForRow(currentContact.name, rowIndex, row);
ContactManager.createCellForRow(currentContact.email, rowIndex, row);
ContactManager.makeTrashbinIcon(row, rowIndex);
}
static createCellForRow(cellInnerHtml, rowIndex, currentRow){
var cell = document.createElement("td");
var input = document.createElement("input");
input.setAttribute("type", "text");
input.setAttribute("class", "hidden");
input.dataset.rowId = rowIndex;
cell.appendChild(input);
var label = document.createElement("label");
label.dataset.rowId = rowIndex;
label.innerHTML = cellInnerHtml;
cell.appendChild(label);
currentRow.appendChild(cell);
}
static makeTrashbinIcon(row, rowIndex){
var cellForTrashbin = row.insertCell();
var trashbin = document.createElement("img");
trashbin.src = "http://i.imgur.com/yHyDPio.png";
trashbin.dataset.rowId = rowIndex;
cellForTrashbin.appendChild(trashbin);
}
static findContactByRowId(element){
var rowId = element.dataset.rowId;
var row = document.getElementById(rowId);
var nameCell = row.firstChild;
var labelForName = nameCell.lastChild;
var name = labelForName.innerHTML;
var emailCell = nameCell.nextSibling;
var labelForEmail = emailCell.lastChild;
var email = labelForEmail.innerHTML;
var contact = new Contact(name, email);
return contact;
}
}
function addEventListenerForTrashbinIcon(){
var table = document.getElementById("table");
var allRows = table.rows;
for(var i=1; i<allRows.length; i++){
var trashbinCell = allRows[i].lastChild;
var trashbin = trashbinCell.firstChild;
trashbin.addEventListener("click", function(evt){
var contactForRemove = ContactManager.findContactByRowId(evt.target);
cm.remove(contactForRemove);
displayWarningMessage();
cm.displayContactsAsATable("contacts");
});
}
}
function addEventListenerToTableCells(){
var table = document.getElementById("table");
var allRows = table.rows;
for(i=1; i<allRows.length; i++){
var currentRow = allRows[i];
var rowCells = currentRow.cells;
var nameCell = rowCells[0];
var emailCell = rowCells[1];
nameCell.addEventListener("click", makeCellEditable);
emailCell.addEventListener("click", makeCellEditable);
}
}
function makeCellEditable(evt){
var input = evt.target.parentNode.firstChild;
evt.target.classList.add("hidden");
input.classList.add("shown");
input.focus();
input.addEventListener("blur", showTableWithChange);
}
function showTableWithChange(evt){
var input = evt.target;
var inputValue = input.value;
if(inputValue == ""){
cm.displayContactsAsATable("contacts");
return;
}
var oldContact = ContactManager.findContactByRowId(input);
var label = input.nextSibling;
label.innerHTML = inputValue;
var newContact = ContactManager.findContactByRowId(input);
cm.remove(oldContact);
cm.add(newContact);
cm.displayContactsAsATable("contacts");
displayWarningMessage();
}
function displayWarningMessage(){
var messegeDiv = document.getElementById("warningMessage");
messegeDiv.style.display = "block";
setTimeout(function(){
messegeDiv.style.display = "none";
}, 2000);
}
function showHideArrow(){
var allArrows = document.querySelectorAll(".arrow");
switch(cm.sortedBy){
case "nameAlphabetical":
var downArrow = document.getElementById("dArrName").classList.add("hidden");
toggleClassHidden(allArrows);
break;
case "nameReverse":
var upArrow = document.getElementById("uArrName").classList.add("hidden");
toggleClassHidden(allArrows);
break;
case "emailAlphabetical":
var downArrow = document.getElementById("dArrEmail").classList.add("hidden");
toggleClassHidden(allArrows);
break;
case "emailReverse":
var upArrow = document.getElementById("uArrEmail").classList.add("hidden");
toggleClassHidden(allArrows);
break;
}
}
function toggleClassHidden(arr){
arr.forEach(function(el){
el.classList.toggle("hidden");
});
}
function addEventListenerToTableHead(){
var columnForNames = document.getElementById("columnForNames");
var columnForEmails = document.getElementById("columnForEmails");
columnForNames.addEventListener("click", sortContactManagerByName);
columnForEmails.addEventListener("click", sortContactManagerByEmail);
}
function sortContactManagerByName(){
if(cm.sortedBy !== "nameAlphabetical"){
cm.sortedBy = "nameAlphabetical"
}
else {
cm.sortedBy = "nameReverse";
}
cm.sort();
cm.displayContactsAsATable("contacts");
}
function sortContactManagerByEmail(){
if(cm.sortedBy !== "emailAlphabetical"){
cm.sortedBy = "emailAlphabetical"
}
else {
cm.sortedBy = "emailReverse";
}
cm.sort();
cm.displayContactsAsATable("contacts");
}
JS.Templates.Contact manager /EdX's JavaScript Introduction Course by W3Cx/
---------------------------------------------------------------------------
A [Pen](https://codepen.io/Onlyforbopi/pen/Xxrgvq) by [Pan Doul](https://codepen.io/Onlyforbopi) on [CodePen](https://codepen.io).
[License](https://codepen.io/Onlyforbopi/pen/Xxrgvq/license).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" type="text/css" href="styles.css"/>
<link rel="stylesheet" type="text/css" href="layouts.css"/>
<title>Contact manager</title>
</head>
<body>
<div class="container">
<div id="warningMessage">Unsaved changes!</div>
<div class="form-container">
<form onsubmit="return formSubmitted();">
<fieldset>
<legend>Personal information</legend>
<label>
Name:
<input type="text" id="name" required>
</label>
<label>
Email:
<input type="email" id="email" required>
</label>
<br>
<button>Add new Contact</button>
</fieldset>
</form>
</div>
<div class="search-container">
<fieldset>
<legend>Search:</legend>
<label>Name:
<input id="search" type="text"/>
</label>
</fieldset>
</div>
</div>
<div>
<h2>List of contacts</h2>
<div id="contacts"></div>
<p>
<button onclick="emptyList();">Empty</button>
<button onclick="cm.save();">Save</button>
<button onclick="loadList();">Load</button>
</p>
</div>
<script src="script.js"></script>
</body>
</html>
以上是关于html JS.Templates.Contact manager / EdX的W3Cx JavaScript入门课程/的主要内容,如果未能解决你的问题,请参考以下文章
Html.Partial 与 Html.RenderPartial 和 Html.Action 与 Html.RenderAction