VisualStudioCode_Day_09
#
html 태그안에 속성을 하지 않는 것이 좋습니다.
따로 빼서 처리하는 것이 좋습니다. css로
◐1-1◐ javascript12.html
testfun()에 대한 함수처리
pagemove()에 대한 함수처리
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link href="../css/basic.css" rel="stylesheet" />
<script src="../js/jstest.js" ></script>
<!-- <script src="../js/jstest.js" ></script> //1)
<script src="../js/jstest.js"/> //2)
1)번과 2번은 동일합니다.
-->
<script>
</script>
</head>
<body>
<form action="" method="get" name="test" onsubmit="return testfun()">
아이디 : <input type="text" name="uid"><span class="span"></span><br>
이름 : <input type="text" name="uname"><br>
<input type="submit" value="등록">
<!-- <input type="button" value="전송" onclick="location.href='javascript3.html'"> -->
<input type="button" value="전송" onclick="return pagemove()">
<!--
1)번 방법 - 잘못된 기능은 아니지만, 추천하지 않습니다.
<input type="button" value="전송" onclick="location.href='javascript3.html'">
onclick="location.href='javascript3.html'"
window.location.href 원칙입니다.
location.href 브라우저라서 생략가능.
2번 방법 -
-->
<!--
action : jsp파일이름 기재
method : get 방식 ->
post방식 ->
-->
</form>
</body>
</html>
◐1-2◐ jstest.js
javascript12안에 있는 호출을 잘라서, jstest에 넣어둔다.
jstest의 함수를 javascript12안에서 호출 한다.
function testfun(){
const uid = document.querySelector('[name=uid]'); //쌍따옴 또는 홑따옴 사용안하면 실행 안됩니다.
// var uid = document.querySelector('[name=uid]'); //범위가 불명확하다.
// let uid = document.querySelector('[name=uid]'); //범위가 명확해서 최신에 개발에서는 주로 사용됩니다.
const uname = document.querySelector('[name=uname]');
const span = document.querySelector('.span');
//선언, 미리읽어와주는 것들은 위에다가 선언하는 것이 좋습니다.
if(uid.value===""){
alert("아이디를 입력하세요...");
uid.focus();
return false;
}
if( !(uid.value.length >=5 && uid.value.length <=8)){
span.textContent = ' 5 ~ 8 사이의 값을 입력 ';
span.style.color='red';
uid.focus();
return false;
}else{ // span삭제
span.textContent = "";
}
if(uname.value===""){
alert("이름을 입력하세요...");
uname.focus();
return false;
}
alert('입력을 처리합니다.')
return true;
}
function pagemove(){
// window.location.href = ""../html/javascript3.html";
location.href = "../html/javascript3.html";
}
◐2-1◐eventfun.js >>> 마무리를 짓지 못했습니다.
let myClick = function(){
const span = document.querySelector('span'); //상수 권장
//let span = document.querySelector('span'); 범위 명확 (권장())
//var span = document.querySelector('span'); 범위 불명확 (비권장)
span.textContent ='클릭을 눌렀군요...';
//span.innerHTML='<h1> 클릭을 눌렀군요.. </h1>'; - 비권장
let myDoubleTest = function(){
const p = document.querySelector('[name=p]'); //지금은 p이지만 클래스로 처리하는 것이 중요
let count=1;
p.textContent += '더블 클릭 ';
p.textContent += count++;
}
}
◐2-2◐ javascript14.html >>> 마무리를 짓지 못했습니다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../js/eventfun.js" ></script>
<!-- 스크립트 아무대나 가도되지만,
되도록이면 위에 처리해주면 좋습니다.
-->
<script>
</script>
</head>
<body>
<h1 ondblclick="myDoubleTest()" name="p">더블클릭</h1>
<p></p><!-- 더블클릭 할 때마다 누적해서 글자가 연속적으로 써지게 -->
<h2 onclick="myClick()">여기를 클릭하면 아래에 글자가 써짐</h2>
<span></span><!-- 클릭을 눌렀군요.... -->
</body>
</html>
◐3◐javascript15.html >>> json예제
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../js/eventfun.js" ></script>
<script>
/*
객체 : 자바스크립트에서 여러 자료를 다룰 때 사용
let 객체명 = { }
const 객체명 = { }
var 객체명 = { }
let 객체명 =[{
키 : 값,
키 : 값,
...
},
{
}
]
*/
let student = {
name : '홍길동',
age : 23,
hubby : function(hub){ //메소드, 객체안에 선언되는 함수를 메소드라고 함
alert(this.name + '님의 취미는 ' + hub + '입니다.');
alert(student.name + '님의 취미는' + hub);
}
}
// alert(student.name);
// student.name="이강산";
// alert(student.hubby('등산'));
//추가
student.ssn = 202402;
// document.write(student.name);
// document.write(student.ssn);
//삭제
delete student.name;
document.write(student.name);
document.write(student.age);
</script>
</head>
<body>
</body>
</html>
◐4◐javascript16.html >>> json 개념
<script>
/*
JSON 객체 : JavaScript Object Notation
자바스크립트의 객체 처럼 자료를 표현하는 방식
주의) 객체
let obj = {
name : '홍길동',
age : 23
}
json객체
{
"name" : "홍길동",
"age" : 23
}
값을 표현할 때는 문자열, 숫자, 불 자료형만 사용 가능
함수 사용할 수 없음
문자열은 반드시 큰따옴표로 묶어야 함
키(=속성)에도 반드시 큰따옴표를 붙여야 함
대부분의 프로그래밍 언어에서는 JSON 형식의 문자열을 읽어들이는 기능이 있음
네트워크를 통해서 각각의 프로그래밍 언어로 만든 애플리케이션들이 데이터를
교환할 때 활용
자바스크립트 객체를 JSON 문자열로 변환할 때 JSON.stringify()메소드 사용
JSON 문자열을 자바스크립트 객체로 전개할 때는 JSON.parse()메소드를 사용
*/
const student =[
{
name : "홍길동",
age : 23,
grade : "A"
},
{
name : "이강산",
age : 30,
grade : "B"
}
]
//student 객체를 JSON 객체로 변환
// JSON.stringify(데이터, 객체에서 어떤 속성만 선택해서 추출하고 싶을 때 사용하나 대부분
// null을 사용, 들여쓰기 칸수)
//JSON.stringify(데이터, null, 들여쓰기칸수); //
alert(JSON.stringify(student, null, 4)); //alert - 안내바
console.log(JSON.stringify(student, null, 2)); //f12 -console에서 확인
document.write(JSON.stringify(student, null, 2)); //화면
//JSON 문자열을 자바스크립트 객체로 변환(전개 ) : JSON.parse()
let json = JSON.stringify(student, null, 4);
console.log(JSON.parse(json));
</script>
◐5◐javascript17.html >>> 클릭시 횟수증가, 오른쪽 마우스 클릭 방지
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
h1{
user-select: none ;/* 마우스 드래그 방지(h1 더블클릭하면 색갈이 바뀌는 것 방지)*/
} /* 즉 글자 전체가 선택 되는 것 방지*/
</style>
<script>
//window.onload = function(){ }
document.addEventListener('DOMContentLoaded', function(){
const h1 = document.querySelector('h1');
let counter = 0;
// contextmenu : 마우스 오른쪽 버튼 이벤트
// 이벤트 막기 : 문서객체.preventDefault();
h1.addEventListener('contextmenu',function(event){
event.preventDefault(); //h1태그에서 마우스 오른쪽 막음
});
h1.addEventListener('click', function(){
counter++;
h1.textContent = '클릭횟수 : ' + counter;
});
});
</script>
</head>
<body>
<h1>클릭 횟수 : 0 </h1>
</body>
</html>
◐6◐javascript18.html >>> 마지막요소 제거
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
//window.onload = function(){ }
document.addEventListener('DOMContentLoaded', function(){
const fruits = ['사과', '딸기', '감', '복숭아', '키위'];
const h1 = document.querySelector('#test'); //'.클래스', '#아이디', '태그', '[속성=값]'
// h1.textContent = fruits;
// join(연결에 사용할 문자)
//h1.textContent = fruits.join('*');
//ex) 사과*딸기*감*복숭아*키위
// pop() : 맨 마지막 요소 제거
// h1.textContent = fruits.pop(); //제거되는 요소 출력
fruits.pop();
h1.textContent = fruits; // 제거 후 요소들
//# 배열.sort() 오름차순 정렬 (사전 순)
h1.textContent = fruits.sort();
//역으로 배열.reverse() ['사과', '딸기', '감', '복숭아', '키위']
fruits.reverse(); //['키위','복숭아','감','딸기','사과']
h1.textContent = fruits;
});
</script>
</head>
<body>
<h1 id="test"></h1>
</body>
</html>
◐7◐javascript19.html >>> 버튼눌러서 정렬되는 것
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
function butFun1(){
const arr=[5, 15, 3, 65, 97, 27];
const button = document.querySelector('.but1');
arr.sort(function(a, b){return a-b}); // 숫자 오름차순 정렬
//문자처럼 정리되었습니다.
//arr.sort(); //숫자도 문자처럼 첫 글자로 정렬
button.textContent = arr;
}
</script>
</head>
<body>
<h1>버튼을 눌러 정렬하기</h1>
<!-- button 태그는 form 태그 안에서 사용할 때 type을 지정하지 않으면 submit 으로 처리
form태그 밖에서는 button 기능이 됨
-->
<button class="but1" onclick="butFun1()">정렬되는 내용</button>
</body>
</html>