JavaScript, Vue.js, CSS/JavaScript
[JavaScript] 실습했던 내용
삶_
2022. 8. 1. 17:48
시계만들기
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.clock {
display: flex;
background-color: yellow;
}
.clock > div{
margin-left: 10px;
font-size: 25px;
}
</style>
<script>
window.onload = function() {
// 실시간 확인 시계
// 1000, 즉 1초로 하면 조금 버퍼링이 걸릴수있어서 그거보다 작게.
setInterval(function(){
// 날짜가져오기
let now = new Date();
// console.log("now", now); // 영어로 월일, 연도, gmt 한국 표준시 출력
// console.log("now.getTime()", now.getTime()); //
// console.log("now.getTime()", now.toISOString()); //날짜, 시간 출력
// console.log("연도", now.getFullYear());
document.getElementById("y").innerHTML = now.getFullYear() + "년";
// console.log("월", now.getMonth()+1); //월은 1 적게 나와서 더해줘야함
document.getElementById("mon").innerHTML = now.getMonth()+ 1 + "월";
// console.log("일", now.getDate());
document.getElementById("d").innerHTML = now.getDate() + "일";
// console.log("시", now.getHours());
document.getElementById("h").innerHTML = now.getHours() + "시";
// console.log("분", now.getMinutes());
document.getElementById("min").innerHTML = now.getMinutes() + "분";
// console.log("초", now.getSeconds());
document.getElementById("s").innerHTML = now.getSeconds() + "초";
}, 250);
let now2 = new Date().toISOString();
document.querySelector("#iso").innerHTML = now2;
let h = now2.split("T")[1].split(":")[0];
console.log(parseInt(h)+9); //문자+숫자
console.log(Number(h)+9);
console.log(parseInt("abc"));
if(isNaN(h)){
console.log("숫자 아님");
}
}
</script>
</head>
<body>
<h1>현재 시각은...</h1>
<div class="clock">
<div id="y">
년
</div>
<div id="mon">
월
</div>
<div id="d">
일
</div>
<div id="h">
시
</div>
<div id="min">
분
</div>
<div id="s">
초
</div>
</div>
<div>
<div id="iso"></div>
</div>
</body>
</html>
버튼 누를때 페이지 달라지는 거
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.header {
background-color: red;
/* display: none; */
color: white;
text-align: center;
padding: 70px;
}
.hea {
/* display: none; */
}
.header > #title {
font-size: 40px;
font-weight: bold;
margin-bottom: 20px;
}
.content {
display: flex;
justify-content : space-evenly;
}
.content > div {
cursor:pointer;
font-size: large;
text-align: center;
color: white;
background-color: rgb(97, 97, 97);
width: 100%;
padding: 20px;
}
#about {
background-color: red;
}
</style>
<script>
window.onload = () => {
let headers = document.querySelectorAll(".hea");
let contents = document.querySelectorAll(".con");
let colors = ["red", "green","blue","yellow"];
let titlelist = ["About", "Products", "Technology", "Downloads"];
let conlist = ["Custom Software Developement Company",
"Building tailored software to address critical needs of global enterprises.",
"Machine Learning, Artificial Intelligent, Cloud Platform.",
"You can download a free 10 days trial."]
for (let i = 0; i < contents.length; i++) {
contents[i].addEventListener('mouseover', function (event) {
if (event.target.style.backgroundColor == "rgb(97, 97, 97)"){
event.target.style.backgroundColor = "gray";
}
});
contents[i].addEventListener('mouseout', function () {
if(contents[i].style.backgroundColor == "gray")
contents[i].style.backgroundColor = "rgb(97, 97, 97)";
});
if (contents[i].style.backgroundColor == "rgb(97, 97, 97)") {
contents[i].addEventListener('mouseout', function () {
contents[i].style.backgroundColor = "rgb(97, 97, 97)";
});
}
contents[i].addEventListener('click', function () {
contents[i].style.backgroundColor = colors[i];
for (let j = 0; j < contents.length; j++) {
if (j != i) {
contents[j].style.backgroundColor = "rgb(97, 97, 97)"
} else {
document.querySelector(".header").style.backgroundColor = colors[i];
}
headers[0].style.display = "block";
headers[1].style.display = "block";
headers[0].innerHTML = titlelist[i];
headers[1].innerHTML = conlist[i];
}
});
}
};
</script>
</head>
<body>
<div class="header">
<div class="hea" id="title">About</div>
<div class="hea" id="text">Custom Software Developement Company</div>
</div>
<div class="content">
<div class="con" id="about">About</div>
<div class="con" id="products">Products</div>
<div class="con" id="technology">Technology</div>
<div class="con" id="downloads">Downloads</div>
</div>
</body>
</html>
JSON 기초
// 객체 -> JSON
//stringify
let json = JSON.stringify(true); //true
//배열 -> JSON
json = JSON.stringify(['apple','banana']); //["apple","banana"]
const rabbit = {
name: 'tori',
size: null,
birthDate: new Date(),
jump: () => {
console.log('${name} can jump!');
},
};
// 객체 출력
// 출력됨 : {"name": "tori", "size": null, "birthDate": "(날짜..생략)"
// jump 같은 함수는 오브젝트에 포함되지 않으므로 출력시 반영되지 않는다
// 자바스크립트의 심볼 기능도 JSON에서 지원되지 않음
json = JSON.stringify(rabbit);
console.log(json);
json = JSON.stringify(rabbit, ["name"]);
console.log(json); // {"name":"tori"} 출력
json = JSON.stringify(rabbit, (key,value) => {
console.log('key: ${key}, value: ${value}');
return value;
});
//위 출력
//key: , value: [object object] //제일 최상위권이 출력됨
//key : name, value: tori
//key : color, value: white
//key : size, value: null
//key : birthDate, value: (날짜..생략)
//JSON -> 객체
json = JSON.stringify(rabbit);
const obj = JSON.parse(json);
console.log(obj);
rabbit.jump(); //함수 출력됨
//obj.jump(); //에러. 객체로 변환 전 이미 JSON화 되었을 때 함수가 지워져있기 때문에
//콜백함수 지정
//console.log(obj.birthDate.getDate()); 하면 오류남. (Date 안의 메서드를 쓰면 오류가 남)
//이유 : JSON을 거쳐가 birthDate 값이 String 형태로 이미 날짜가 출력되었기 때문에 Date 가 존재하지 않기 때문
//새로 만들어줘야 함
const obj2 = JSON.parse(json, (key,value) => {
console.log('key: ${key}, value: ${value}');
return key === 'birthDate' ? new Date(value) : value;
});
JSON - XMLHttpRequest
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
caption {
display: none;
}
</style>
<script>
window.onload = () => {
bind();
}
//1. 버튼 클릭
function bind() {
document.querySelector("#view").addEventListener('click', getBoard);
};
//2. ajax를 통해서 json 로딩
function getBoard() {
// 서버로부터 요청받은 xml 데이터 저장하는곳
let xhr = new XMLHttpRequest();
// 메서드(형태로), 주소에서 반환함
xhr.open("get", "text.json");
// 요청 전달
xhr.send();
xhr.onload = function () {
// responseText : 요청 후 응답으로 받은 데이터 -> 문자열로 반환
console.log(xhr.responseText);
// 문자열이 된 데이터들을 JSON 형태로 변환
let data = JSON.parse(xhr.responseText);
drawBoard(data);
}
};
//3. 로딩된 json으로 테이블 내용 표시
function drawBoard(json) {
if (json) { //json == true 이면, 데이터가 존재하면
console.log(json);
// json은 배열 데이터이다
let html = "";
for (let i = 0; i < json.length; i++) {
let data = json[i];
html += "<tr>";
html += " <td>" + data.id + "</td>";
html += " <td>" + data.title + "</td>";
html += " <td>" + data.author + "</td>";
html += " <td>" + data.like + "</td>";
html += "</tr>";
}
document.querySelector("#board_body").innerHTML = html;
}
}
</script>
</head>
<body>
<h1>게시판 내용을 동적으로 표시</h1>
<button type="button" id="view">내용 표시</button>
<br>
<table border="1">
<caption>게시글 표시</caption>
<thead>
<tr>
<th>번호</th>
<th>제목</th>
<th>글쓴이</th>
<th>좋아요</th>
</tr>
</thead>
<tbody id="board_body">
</tbody>
</table>
</body>
</html>