본문 바로가기
개발자로 가는 길(국비지원과정)/3.HTML,CSS,JavaScript, jQuery

[210625금] 숫자 검증, trim함수, select 함수, value와 innerHTML의 차이, <자바스크립트의 주요 데이터 종류>, 자바스크립트 정리

by 레아Leah 2021. 6. 25.
반응형

<지역변수와 전역변수의 차이점>

-지역변수: 지역 안에서 선언되어 지역 밖에서는 접근 불가

-전역변수: 문서 내에서 모든 함수에서 접근가능한 변수

 

 

<검증해야 할 것> 

이름 : 반드시 입력할 것 

나이: 숫자여야하고 문자가 포함되면 안된다. 

키: 숫자여야하고 문자가 포함되면 안된다. 

몸무게: 숫자여야하고 문자가 포함되면 안된다. 

 

BMI 계산 후 #result에 삽입

 

더보기

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
function checkData(){
let username = document.getElementById("username").value;
let age= document.getElementById("age").value;
let height= document.getElementById("height").value;
let weight= document.getElementById("weight").value;

alert(username);
}
</script>
</head>
<body>
<div class="wrapper">
<h2>[숫자 정보 검증]</h2>
<div id= "result">결과 : </div>
<form>
<table border="1">
<tr>
<th>이름</th>
<td>
<input type="text" id="username">
</td>
</tr>
<tr>
<th>나이</th>
<td>
<input type="text" id="age">
</td>
</tr>
<tr>
<th>키</th>
<td>
<input type="text" id="height">
</td>
</tr>
<tr>
<th>몸무게</th>
<td>
<input type="text" id="weight">
</td>
</tr>
<tr>
<th colspan="2">
<input type="button" id ="check" value="검증하기" onclick="checkData();">
<input type="button" id ="clear" value="삭제하기"  onclick="formClear();">
</th>
</tr>
</table>
</form>
</div>
</body>
</html>


 

 

let username = document.getElementById("username")는 태그를 긁어오는 것 

값을 가져오고 싶으면  let username = document.getElementById("username").value;

 

[이름]

이름이 잘 가져와지는지 alert을 통해 확인하기 

 

 

공백 " ", "    "이 들어가도 이름이라고 인식하는 경우가 있기때문에 공백을 포함하지 못하게 trim을 사용해준다. 

 

 

[나이]

alert창 띄어 잘 가져오는지 확인

 

isNaN(데아터) 

: "", "23/" ==> isNaN(age) 문자가 포함되었니? 포함되었으면 true 

 

select()

: 입력상자의 내용을 선택해주는 함수 

: 태그.select();

 

select함수는 태그 뒤에만 사용할 수 있기 때문에 

document.getElementById("age").select(); 

 

키와 몸무게 또한 동일하게! 

 

검증을 했을 뿐 계산할 수 없다 

 

parseInt()

: 문자열 안에 있는 정보를 정수로 변환

 

parseFloat()

 

차이를 이해하기 위한 코드! 

alert(parseInt("34.5") + ", " + parseFloat("34.5"))

 

 

소수점 이하가 너무 많이 나오니 bmi = Math.floor(bmi*100) / 100; 사용 ! 

소수점 아래 2자리까지, 세자리를 원한다면 1000으로

 

 

BMI 알림 메시지

 

시작 태그와 끝 테그에 꽂아넣을 때 사용하는 것은 innerHTML

value가 아니라는 점 주의

끝태그가 없는 경우에는 innerHTML을 사용할 수 없다. ex> image or input과 같은 경우 value 

 

 

놀랍게도 작동을 하지 않기 시작했다.. 스펠오류

작동됨

 

 

value은 =의 좌측에 있을 경우, 대입

value가 =의 우측에 있을 경우 값을 가져온다.

=> read, write 둘 다 가능한 메소드! 

form 태그 중에서 사용자가 입력한 값을 가져올 때 사용한다. 

 

 

"삭제하기" 버튼을 누르면 입력한 내용이 전부 사라지게 하는 함수 formClear

 

오류 고친거

 

 

 

새로운 HTML 생성해주세요. 

 

클래스 안에 들어있으면 메소드 

밖에 있으면 함수 

 

 

<자바스크립트의 주요 데이터 종류>

문자열

숫자

불린: true 1, false 0

함수: function, 또한 하나의 데이터 

갹체: {}, []

       html 객체: dociment.getElementById("")

          끝태그가 있는 경우: <div>,,,,</div> =>innerHTML

          끝태그가 없는 경우: <img src="">

           => getAttribute("src")을 통해 값을 가져올 수 있고, setAttribute("src", "cat.jpg")

          폼태그: <input type="text"> => value 함수가 아니라 속성! 

 

 

setInterval();

: 전달인자로 2개를 줄 수 있다 

: 함수를 전달인자로 사용하고 return 값으로도 사용할 수 있다.

: setInterval(function, 밀리세컨드); 이것을 끌때는 claerInterval();로 꼭 꺼줘야 한다.

=> 방법! 

let tmp = setInterval(function, 밀리세컨드); 

c;learInterval(tmp);

 

 

 

 

 

더보기

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
//전역변수 
let tmp; 
function start() {
tmp = setInterval(function() {
console.log("콘솔입니다.");
}, 1000);
}
function stop() {
clearInterval(tmp);
console.log("End");
}
</script>
</head>
<body>
<input type="button" value="시작" onclick="start();">
<input type="button" value="멈춤" onclick="stop();">

<h2 id="current"></h2>
</body>
</html>

 

 

결과

콘솔이 아니라 다른 곳에 

더보기

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script>
//전역변수 
let tmp; 
function start() {
let now = document.getElementById("current");

tmp = setInterval(function() {
let curr = new Date();
let h = curr.getHours();
let m = curr.getMinutes();
let s = curr.getSeconds();

let message = "현재시간: " + h + " : " + m + " : " + s;
now.innerHTML = message; 

}, 1000);
}
function stop() {
clearInterval(tmp);

}
</script>
</head>
<body>
<input type="button" value="시작" onclick="start();">
<input type="button" value="멈춤" onclick="stop();">

<h2 id="current"></h2>
</body>
</html>

 

 

 setInterval은 1초가 지날 때마다 타이머 

1000 밀리세컨드가 지날 때 동안 

 

익명함수 

 

 

<자바스크립트 정리>

-Core  문법: 제어문... 

                 내장객체(Date, String, Array, Math...) 

                  Marh, floor()

 

-BOM(Browser Object Method) 

 location.href

 

-DOM(Document Object Method) ==> innerHTML

반응형