반응형
Javascript로 만드는 [로또 번호 추첨기]
- Javascript 코드는 HTML, JS 파일 내에 쓸 수 있다.
1. JS를 HTML내부에 쓰는 법: 코드는 위에서 아래로 실행되므로 HTML 모두 불러온 다음에 동작시키는 경우가 많아서 바디 태그 끝나는 지점에 자바스크립트 작성할 때가 많다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>JavaScript 사용 방법</title>
</head>
<body>
<h1>JavaScript 사용 방법</h1>
<script>
document.write('코드라이언 짱짱')
</script>
<script src='myScript.js'>이걸로 쓰면 myScript.js에 적힌 내용이 출력됨 </script>
</body>
</html>
2. myScript.js에 쓰는 경우!
document.write("안녕안녕나는보글이~")
- 세미콜론: 하나의 명령어가 끝남을 말한다. 자바스크립트는 유연해서 줄바꿈으로도, 정상적으로 동작
- 주석: //, /**/
- 변수(variable): var 변수명 = 값; let 변수명=값; const 변수명=값;
- 문자열(String)
- 숫자(int, float)
- 불(bool)
- typeof 데이터: 자료형 알 수 있음
- 1~45 공 중 6개 뽑기--> 공1개 뽑기부터 시작!
- Math.random(); =>0이상~1미만의 실수 나옴.
- parseInt=>실수를 정수로 변환
var num = Math.random() * 45 + 1;
var ball1 = parseInt(num);
document.write(ball1);
- Array: var lotto = [1,2,3,4,5,6]; lotto.push(7);
- 6개 만드려면 lotto.push(parseInt(Math.random()*45+1))코드 6번 하면 됨!
- for(var i=0;i<6;i++){lotto.push(parseInt(Math.random()*45+1))}
- .indexOf(값) : 값이 있으면 위치, 없으면 -1
- while(조건){반복}: 특정 조건까지 계속 반복
- .length: 길이
- .sort(): 배열 값 정렬 =>사전순
- .sort((a,b)=>a-b) =>숫자 오름차순
var lotto = [];
while (lotto.length<6){
var num = parseInt(Math.random() * 45 + 1);
if (lotto.indexOf(num) == -1) {
lotto.push(num);
}
}
lotto.sort((a,b)=>a-b);
document.write(lotto);
Javascript로 만드는 [자소서 글자수 계산기]
- DOM(Document Object Model): HTML 코드에 쉽게 접근할 수 있게 만든 모델
- document.getElementById('jasoseol'); =>특정 태그를 선택해서 불러온다.
- document.getElementById('jasoseol').value; =>값 가져오기
- document.getElementById('jasoseol').innerHTML;
- console.log('코드라이언'); //콘솔창에 출력
- textarea 내용 가져와서 content에 저장!
- .length: 문자열의 길이 알 수 있다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>자소서 글자수 계산기</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<style>
h1 {
margin-top: 30px;
}
#count {
float: right;
}
</style>
</head>
<body class="container">
<h1>자기소개</h1>
<textarea class="form-control" rows="3" id="jasoseol">저는 인성 문제가 없습니다.</textarea>
<span id="count">(0/200)</span>
<script>
var content = document.getElementById('jasoseol').value;
document.getElementById('count').innerHTML='('+content.length+"/200)";
</script>
</body>
</html>
- function 함수이름(){ 명령어1; 명령어2;} => 호출 : 함수이름();
- 이벤트 핸들링: 이벤트 발생하면 ~하라. ex)키보드를 누를 때마다, 글자 수를 세주어라
- <textarea 이벤트=이벤트핸들링></textarea>
- .substring(0,5):0이상 5미만
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>자소서 글자수 계산기</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<style>
h1 {
margin-top: 30px;
}
#count {
float: right;
}
</style>
</head>
<body class="container">
<h1>자기소개</h1>
<textarea onkeydown='counter();' class="form-control" rows="3" id="jasoseol">저는 인성 문제가 없습니다.</textarea>
<span id="count">(0/200)</span>
<script>
function counter(){
var content = document.getElementById('jasoseol').value;
if(content.length >200){
content=content.substring(0,200)
document.getElementById("jasoseol").value=content;
}
document.getElementById('count').innerHTML='('+content.length+"/200)";
};
counter();
</script>
</body>
</html>
Javascript로 만드는 [미니 스타크래프트]
- Jquery 장점:
- 간결한 문법
- 편리한 API
- 크로스 브라우징- 사파리, 크롬 전부 동일한 기능 제공
- $(선택자).행위; $('#content').val(); => id가 content인거의 val가져오기
- onclick="hello();" == $('#click').click(hello) ->click이라는 id가진 버튼 클릭하면 hello라는 함수 실행됨
- 익명함수:
$('#click').click(function(){ console.log('hello');});
- fadeIn() : 나타나게 함
- animate(properties) : 움직이기 //$() .animate {left: +=250}
- fadeOut(): 사라지게 함
- css(): css({left:'150px'});
- callback-->함수 모두 끝나고 다음 함수 실행 =>fadeOut안쪽이 익명함수 만들어서 fadeOut끝나고 익명함수 실행되도록!
var hp = 3;
$('#drone').click(function(){
$('#spit').fadeIn();
$('#spit').animate({left: '+=250'});
$('#spit').fadeOut(function(){
hp = hp - 1;
$('#hp').text('HP: ' + hp);
if(hp==0){
$('#bunker').fadeOut();
}
});
$('#spit').css({left: '150px'}); //원래로 되돌리기
});
Javascript로 만드는 [기념일 계산기]
- 객체(Object)
- var person={name:''he", age:20} //함수, 배열 다 들어갈 수 있음.
- '객체.key'로 값을 가져올 수 있음. person.name
- var now=new Date();
- now.getMonth();, now.getDate();
//1. Date 객체 생성
var now = new Date();
//2. 연도를 가져오는 메서드 .getFullYear()
console.log(now.getFullYear());
//3. 월 정보를 가져오는 메서드 .getMonth() {0: 1월, 1: 2월, ... 10: 11월, 11: 12월}
console.log(now.getMonth());
//4. 일 정보를 가져오는 메서드 .getDate()
console.log(now.getDate());
//5. 1970년 1월 1일 00:00:00을 기준으로 흐른 시간을 밀리초로 표시하는 메서드 .getTime()
console.log(now.getTime());
//6. 특정 일의 Date 객체 생성
var christmas = new Date('2020-12-25');
console.log(christmas);
//7. 특정 ms의 Date 객체 생성
var ms=new Date(1000);
console.log(ms);
var now = new Date();
var start = new Date('2020-06-30');
var timeDiff = now.getTime() - start.getTime();
var day = Math.floor(timeDiff / (1000 * 60 * 60 * 24) + 1);
$("#love").text(day + "일 째")
- Math.floor: 소숫점 날리기
- 만난 일 계산기
var valentine = new Date('2022-02-14');
var timeDiff2 = valentine.getTime() - now.getTime();
var day2 = Math.floor(timeDiff2 / (1000 * 60 * 60 * 24) + 1);
$('#valentine').text(day2 + '일 남음');
- 1000일 계산기
var ms = start.getTime() + 999 * (1000 * 60 * 60 * 24);
var thousand = new Date(ms);
var thousandDate = thousand.getFullYear() + '.' + (thousand.getMonth()+1) + '.' + thousand.getDate();
$('#thousand-date').text(thousandDate);
- 1000일 까지 며칠 남았는지 계산
var timeDiff3 = thousand.getTime() - now.getTime();
var day3 = Math.floor(timeDiff3 / (1000 * 60 * 60 * 24) + 1);
$('#thousand').text(day3 + '일 남음');
반응형