<script>
태그<script></script>
태그 안쪽의 태그를 JS로 해석<script>
document.write(1+1)
</script>
document.write()
: JavaScript 출력문<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<input type="button" value="hi" onclick="alert('hi')">
<input type="text" onchange="alert('changed')">
<input type="text" onkeydown="alert('key down!')">
</body>
</html>
JavaScript 언어의 타입은 원시 값
과 객체
로 나뉨
(하단 참고)
산술연산자
: 피연산자에 대해 사칙연산을 포함한 각종 산술연산을 수행하는 연산자로 이항연산자
와 단항연산자
로 구분이항연산자
: 2개의 자료를 대상으로 산술적인 처리를 수행하는 연산자로, +
,-
,*
,/
등을 포함이항연산자
로 계산될 수 있음""
또는 ''
안에 입력됨str.length
: str의 글자수 반환str.toUpperCase()
: 대문자로 반환str.indexOf(searchValue[, fromIndex])
: index number 반환 (0부터 시작 / 괄호 안이 str일 경우 맨 앞 글자의 index number)str.trim()
: str 앞뒤 공백 없앰x=1;
변수
, =는 대입연산자
1=2;
상수
이기 때문)var name = 'leezche';
alert("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut dignissim massa quis lacus "+name+" tempus malesuada. Nulla condimentum magna nec semper sodales. Suspendisse aliquam at nibh eget lacinia. Proin ultrices lacus dui, sit amet elementum sapien luctus ut. Vestibulum ante ipsum primis in faucibus orci "+name+" luctus et ultrices posuere cubilia curae; Etiam bibendum, velit vel auctor faucibus, purus ligula auctor nisi, vitae venenatis nibh urna nec felis. Donec ex nisi, dictum in blandit vel, posuere in mi. Nullam vel placerat erat, eget porta diam. Vestibulum hendrerit lorem ac lacus "+name+" ornare, quis convallis justo efficitur.")
var
키워드를 써야 함<body>
태그의 style 속성에 CSS 값 넣어줘야 함<h2 style="">JavaScript</h2>
태그 안에 style 속성을 쓰고 그 안에 CSS 사용
이름 | 기능 |
---|---|
<div> | CSS나 JS를 통해 어떤 정보를 제어하고 싶을 때 그것을 감싸주는 태그 - 웹페이지 전체를 쓰는 태그여서 줄바꿈 가능 |
<span> | <div> 태그와 동일한 기능이지만 줄바꿈이 안됨 |
<style> | <script> 태그처럼 <style> 태그 안의 텍스트가 CSS라는 것을 웹브라우저에게 알려주는 역할을 하는 구분자 |
<span>
태그 안의 class 속성 값이 js인 태그에 대한 것이면, <style>
태그 안에 .js{ } 입력하고 그 안에 CSS 입력<span>
태그 안의 id
속성 값이 first인 태그에 대한 것이면, <style>
태그 안에 #first{ }
입력하고 그 안에 CSS 입력<span id="first" class="js">JavaScript</span>
Q. 위의 <span>
태그는 id
와 class
의 영향 둘다 받는데 왜 초록색으로 나타날까?
id
와 class
의 의미 차이를 봐야 함. id
= 어떤 한 가지 대상을 식별class
= 어떤 대상들을 그룹핑id=”first”
가 한 번 등장했다면 그 코드 안에서 id=”first”
는 더 이상 쓰면 안됨class
가 id
보다 포괄적; class
지정하고 id
는 예외적으로 사용id
가 class
보다 우선순위Q. 웹페이지의 모든 <span>
태그에 대해 파란색을 하고 싶다
-> <style>
태그 안에 span
입력하고 그 안에 CSS 입력 (span
앞에 아무것도 안 붙임)
id
, class
가 영향 주는 <span>
태그의 경우 id
가 더 우선순위id
> class
> span
순으로 우선순위 <h1><a href="index.html">WEB</a></h1>
<input type="button" value="night" onclick="
document.querySelector('body').style.backgroundColor='black';
document.querySelector('body').style.color='white';
">
<input type="button" value="day" onclick="
document.querySelector('body').style.backgroundColor='white';
document.querySelector('body').style.color='black';
">
(1) 어떻게 버튼을 누르면 body 태그 전체를 선택?
var el = document.querySelector(".myclass");
-> 웹페이지에 있는 모든 태그 중 class명이 myclass인 태그를 선택하는 선택자
이 경우 body 태그를 직접 선택할 것이기 때문에 document.querySelector(‘body’)
(2) 어떻게 선택한 body 태그 전체 대상으로 style 속성을 어떻게 JS로 넣을 수 있나?
https://www.w3schools.com/jsref/dom_obj_style.asp
https://www.w3schools.com/jsref/prop_style_backgroundcolor.asp
위의 2개 자료를 참고해서 document.querySelector(‘body’).style.backgroundColor=’black’;
(CSS에서는 background-color인데 JS에서는 backgroundColor임을 유의)
document.querySelector(‘body’).style.color=’white’;
(그냥 color는 텍스트 색깔)
여기까지 night mode 완성
똑같이 복붙해서 색깔 바꿔주면 day mode 완성
비교연산자
: 피연산자를 서로 비교하고, 비교 결과가 참인지 거짓인지에 따라 Boolean(True, False)를 반환, ===
, <
, >
등이 있음<
는 태그와 위치 겹칠 경우 <
와 같이 쓸 수 있음<input id="night_day2" type="button" value="night" onclick="
if(document.querySelector('#night_day2').value === 'night'){
document.querySelector('body').style.backgroundColor='black';
document.querySelector('body').style.color='white';
document.querySelector('#night_day2').value = 'day'
} else {
document.querySelector('body').style.backgroundColor='white';
document.querySelector('body').style.color='black';
document.querySelector('#night_day2').value = 'night'
}
">
여기에서
(1) document.querySelector('#night_day2')
는 onclick
이벤트가 속해 있는 자기 자신을 가리킴 -> this로 바꿈
(2) document.querySelector('body')
가 중복 ->
var target = document.querySelector('body')으로 변수 설정한 후 밑의 중복되는 부분들을 변수로 대체
변경 후:
<input id="night_day" type="button" value="night" onclick="
var target = document.querySelector('body');
if(this.value === 'night'){
target.style.backgroundColor='black';
target.style.color='white';
this.value = 'day'
} else {
target.style.backgroundColor='white';
target.style.color='black';
this.value = 'night'
}
">
.push()
: 데이터를 array의 끝에 추가count
.length
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>Array</h1>
<h2>Syntax</h2>
<script>
var coworkers = ["egoing","leezche"];
</script>
<h2>get</h2>
<script>
document.write(coworkers[0]);
document.write(coworkers[1]);
</script>
<h2>add</h2>
<script>
coworkers.push('duru');
coworkers.push('taeho');
</script>
<h2>count</h2>
<script>
document.write(coworkers.length);
</script>
</body>
</html>
= i + 1
기존 코드 맨 밑에 추가, while(i < n+1)
반복문의 조건으로 설정while(){ }
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>Loop & Array </h1>
<script>
var coworkers = ['egoing','leezche','duru','taeho', 'graphittie'];
</script>
<h2>Co workers</h2>
<ul>
<script>
var i = 0;
while(i < coworkers.length){
document.write('<li><a href="http://a.com/'+coworkers[i]+'">'+coworkers[i]+'</a></li>');
i = i + 1;
}
</script>
</ul>
</body>
</html>
콘솔 창에서
document.querySelector(‘a’)
: <a>
태그에 해당하는 첫번째 태그만 가져옴.document.querySelectorAll(‘a’)
: <a>
태그에 해당하는 모든 태그를 배열(node list)로 가져옴var alist = document.querySelectorAll(‘a’);
console.log(alist[0]); // 또는 (alist.length)
-> 괄호 안의 결과가 콘솔 창에 출력
반복문을 이용, alist에 있는 태그를 하나하나 꺼내서 그것의 style 속성을 지정하려면? 아래와 같이 콘솔 창에 입력
var alist = document.querySelectorAll('a');
var i = 0;
while(i < alist.length){
console.log(alist[i]);
alist[i].style.color = 'powderblue';
i = i + 1;
}
-> 태그를 화면에 출력할 수 있게 됨
(위쪽 화살표 키 누르면 위에 친 코드가 다시 나타남)
<!doctype html>
<html>
<head>
<title>WEB1 - JavaScript</title>
<meta charset="utf-8">
</head>
<body>
<h1><a href="index.html">WEB</a></h1>
<input id="night_day" type="button" value="night" onclick="
var target = document.querySelector('body');
if(this.value === 'night'){
target.style.backgroundColor='black';
target.style.color='white';
this.value = 'day'
var alist = document.querySelectorAll('a');
var i = 0;
while(i < alist.length){
alist[i].style.color = 'powderblue';
i = i + 1;
}
} else {
target.style.backgroundColor='white';
target.style.color='black';
this.value = 'night'
var alist = document.querySelectorAll('a');
var i = 0;
while(i < alist.length){
alist[i].style.color = 'blue';
i = i + 1;
}
}
">
<ol>
<li><a href="1.html">HTML</a></li>
<li><a href="2.html">CSS</a></li>
<li><a href="3.html">JavaScript</a></li>
</ol>
<h2>JavaScript</h2>
<p>
JavaScript (/ˈdʒɑːvəskrɪpt/), often abbreviated JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of websites use JavaScript on the client side for webpage behavior, often incorporating third-party libraries. All major web browsers have a dedicated JavaScript engine to execute the code on users' devices.
</p>
<input id="night_day2" type="button" value="night" onclick="
if(this.value === 'night'){
document.querySelector('body').style.backgroundColor='black';
document.querySelector('body').style.color='white';
this.value = 'day'
} else {
document.querySelector('body').style.backgroundColor='white';
document.querySelector('body').style.color='black';
this.value = 'night'
}
">
</body>
</html>
function
키워드 붙여서 만듦.function nightDayHandler(){
}
nightDayHandler(this);
로 대체하면 기존의 것보다 훨씬 더 효율적.<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>Function</h1>
<h2>Basics</h2>
<ul>
<script>
function two(){
document.write('<li>2-1</li>');
document.write('<li>2-2</li>');
}
document.write('<li>1</li>');
two();
document.write('<li>3</li>');
two();
</script>
</ul>
<h2>Parameter & Argument</h2>
<h2>Return</h2>
</body>
</html>
sum(left, right)
에서 left
, right
이 파라미터sum(2,3)
에서 2
,3
이 인자<script>
function sum2(left, right){
return left+right;
}
document.write(sum(2,3)+'<br>');
document.write('<div style="color:red">+sum2(2,3)+'</div>');
document.write('<div style="font-size:3rem;">+sum2(2,3)+'</div>');
sum2
함수가 구현함으로써 return
에서 원자화된 기능을 다양한 맥락/용도에서 활용할 수 있는 자유도가 생김객체 만들기 전 과정
(1) 중복된 코드 함수로 독립시키기
setColor
함수 정의 (링크 태그 색깔 변경) -> color 값을 매개변수로 세팅 -> 코드 내용 복붙function setColor(color){
var alist = document.querySelectorAll('a');
var i = 0;
while(i < alist.length){
alist[i].style.color = color;
i = i + 1;
}
}
(2) 함수를 통해 로직에 이름 부여
<body>
태그 의 폰트 컬러 바꾸는 함수 정의function BodySetColor(color){
document.querySelector('body').style.color = color;
}
이미 정의된 함수의 경우 중복 사용되면 앞의 것이 덮어쓰기되어 삭제
이 상황에서 <Body>
라는 객체를 만들어서, 정리정돈하는 '폴더'와 같은 도구로 사용
.
은 object access operator[“ “]
로 assign하고 가져와야 함for(var key in coworkers){}
: coworkers라는 변수가 가리키는 객체에 있는 key 값(programmer
, designer
등)들을 가져와서, 중괄호의 코드를 실행해주는 반복문<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>Object</h1>
<h2>Create</h2>
<script>
var coworkers = {
"programmer":"egoing",
"designer":"leezche"
};
document.write("programmer : "+coworkers.programmer+"<br>");
document.write("designer : "+coworkers.designer+"<br>");
coworkers.bookkeeper = "duru"; // 정보 추가
document.write("bookkeeper : "+coworkers.bookkeeper+"<br>");
coworkers["data scientist"] = "taeho";
document.write("data scientist : "+coworkers["data scientist"]+"<br>");
</script>
<h2>Iterate</h2>
<script>
for(var key in coworkers){
document.write(key+' : '+coworkers[key]+'<br>');
}
</script>
</body>
</html>
showAll
)("programmer":"egoing"
)
coworkers
가 박혀 있는데, 이것을 고치기 위해 showAll
함수 안에서 함수가 소속되어 있는 객체를 가리키는 약속된 기호인 this
로 function 정의 시의 coworkers
를 대체하면 됨showAll
함수 자체도 표시되는데, 이것은 나중에 if문 사용해서 제거 가능<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>Object</h1>
<h2>Create</h2>
<script>
var coworkers = {
"programmer":"egoing",
"designer":"leezche"
};
document.write("programmer : "+coworkers.programmer+"<br>");
document.write("designer : "+coworkers.designer+"<br>");
coworkers.bookkeeper = "duru"; // 정보 추가
document.write("bookkeeper : "+coworkers.bookkeeper+"<br>");
coworkers["data scientist"] = "taeho";
document.write("data scientist : "+coworkers["data scientist"]+"<br>");
</script>
<h2>Iterate</h2>
<script>
for(var key in coworkers){
document.write(key+' : '+coworkers[key]+'<br>');
}
</script>
<h2>Property & Method</h2>
<script>
coworkers.showAll = function(){
for(var key in this){
document.write(key+' : '+this[key]+'<br>');
}
}
coworkers.showAll();
</script>
</body>
</html>
Body
라는 객체 생성setColor
를 지정하고 function 정의해줌var Body = {
setColor:function (color){
document.querySelector('body').style.color = color;
}
setBackgroundColor:function (color){
document.querySelector('body').style.backgroundColor = color;
}
}
<script>
태그 제외하고 code.js
에 복붙<script>
태그 안의 부분(복붙한 부분) 제외하고 <script src="colors.js"></script>
이렇게 만들어주면 똑같은 출력이지만 완전히 다른 구조
colors.js
가 다운로드되어 있는 것 확인 가능colors.js
를 수정하면 그것을 포함한 모든 웹페이지에 자동으로 반영 -> 유지보수 편리, 로직 같음을 알 수 있음, 가독성 높아짐, 서버 입장에서는 비용 절감, 사용자 입장에서 트래픽 절감, 빠른 웹페이지 로딩 속도참고
생활코딩 WEB2-JavaScript
이벤트의 개념
[생활코딩] JavaScript 기본문법 정리 (숫자와 문자, 변수, 주석, 줄바꿈과 여백, 비교)
제4장 연산자(operator)(산술 연산자, 관계 연산자)
객체와 프로퍼티,메소드
5.10 Object 객체