parisangsoo
JS 03/02 본문
자바스크립트를 이용한 간단한 계산기 만들기
1.CSS
<style>
*{margin:0;}
table{border:1px solid black;
border-collapse:collapse;
margin: 10px auto;}
li{list-style:none;
float:left;
margin-left:10px;}
input{border-style:none;}
ul input{border-style:solid;
border-width:0.5px;
width:40px;
margin:0 auto;}
ul input:first-child{magin-left:0;}
</style>
2.JS
<script>
function cal(op){
let su1 = document.getElementById("su1").value;
let su2 = document.getElementById("su2").value;
let result = document.getElementById("result");
let num_check = /^[0-9]+$/; //유효성 체크
if(!num_check.test(su1) || !num_check.test(su2)){ // 정수 유효성 체크
alert("값은 정수만 입력해주세요.");
return;
}
let res;
switch(op){
case "+":
res = Number(su1) + Number(su2);
break; // switch문만 나가고 나머지 아래의 코드를 실행 // result.value = res; 코드 실행
/* +를 제외한 나머지 연산자는 저절로 숫자로 변환됨 */
case "-":
res = su1 - su2;
break;
case "*":
res = su1 * su2;
break;
case "/":
if(su2 == 0){
alert("0으로는 나눌 수 없습니다.")
return; // switch문만 종료하는것이 아니라 함수 전체 아래의 코드를 실행하지 않고 함수 전체를 빠져나옴
}
res = su1 / su2;
result.value = res.toFixed(2); // 소숫점 2번째 자리까지 나타내고 result.value를 갱신 후 함수 전체 종료
return;
} // switch
result.value = res; // 나눗셈에서는 return으로 인해 이 코드를 실행하지 않지만 나머지는 break때문에 코드 실행
} // end of cal()
</script>
3.HTML
<body>
<table border="1">
<tr>
<th class="su">수1</th>
<td><input id="su1"></td>
</tr>
<tr>
<th class="su">수2</th>
<td><input id="su2"></td>
</tr>
<tr>
<td colspan="2">
<ul>
<li><input type="button" value="+" onClick="cal('+');"></li>
<li><input type="button" value="-" onClick="cal('-');"></li>
<li><input type="button" value="*" onClick="cal('*');"></li>
<li><input type="button" value="/" onClick="cal('/');"></li>
</ul>
</td>
</tr>
<tr>
<th class="res">결과</th>
<td><input id="result" readonly="readonly"></td> <!-- readonly : 읽기 전용 text, 값 입력 불가 -->
</tr>
</table>
</body>
자바스크립트에서 태그(요소) 생성하기
1.JS
<script>
let array = ["서울", "대전", "제주"];
//현재 html 문서가 실행되면 자동으로 호출되는 생성자와 같은 영역
//윈도우를 로드하자마자 열리는 함수!
window.onload = function (){
alert("페이지 로드완료");
//sido태그 검색
let sido = document.getElementById("sido");
//위에서 검색된 sido태그에 자식 요소인 opition태그를 생성하여 추가
for( let i = 0; i < array.length; i++){
//option태그를 직접 생성 (createElement : 요소 생성)
let opt = document.createElement("option");
// 생성된 <option>태그에 내용을 추가
opt.textContent = array[i];
//sido태그에 opt를 자식요소로 추가
sido.appendChild(opt);
}
}
</script>
2.HTML
<body>
<select id="sido">
<option>:::선호하는 지역:::</option>
</select>
<hr>
<select name="" id="">
<option>:::메뉴선택:::</option>
<option>메뉴1</option>
<option>메뉴2</option>
</select>
</body>
Comments