windw
자바스크립트의 최상위 객체 BOM, DOM으로 나뉨
- BOM(Brower Object Model) : location(주소관리), screen(창), nevigator(브라우저)
- DOM(Document Object Model) : document
BOM
open
창의특성
width(너비), height(높이)
=> yes | no로 정할 수 있는 옵션들
resizable(창의 크기조절 기능), location(주소창), menuber(메뉴바), scrollbar(스크롤바), status(상태표시줄), toolbar(도구모음) 등
open은 window를 생략하지 않고 사용.(헷갈림 방지)
<button onclick="test1()">네이버</button>
<script>
function test1(){
//window.open(); //새창열기
//window.open(url, 창이름, 옵션);
//window.open("https://www.naver.com");
//창이름 : 브라우저 창의 이름을 부여할 수 있음, 이름에 따라서 동일이름의 창은 1번만 생성됨.
// window.open("https://www.naver.com", "naver");
//옵션 : 너비, 높이, 주소창여부, 툴바...
let popup = window.open("https://www.naver.com", "naver", "width=500, height=500, resizeable=no, location=no");
setTimeout(function(){
popup.close(); //코드를 통해서 브라우저창을 닫을 수 있음.
}, 2000);
}
</script>
setTimeOut
window. setTimeOut(함수, 시간 ms)
<button onclick="test2()">실행</button>
<script>
function test2(){
//const myWindow = window.open();
//myWindow.alert("ㅋㅋㅋㅋㅋㅋㅋ");
// setTimeout(function(){
// myWindow.close();
// }, 3000)
console.log("처음로딩 -> 화면이 그려짐");
console.log("서버에 데이터 요청");
setTimeout(function(){ //서버에서 응답이 2초걸림
console.log("서버에서 응답도착");
console.log("응답데이터를 가지고 화면을 구성");
},2000)
console.log("데이터없이 화면의 틀을 미리 구성");
}
</script>
setInterval
window.setInterval(함수, 시간 ms);
<button onclick="test3()">실행</button>
<div id="area1" class="area"></div>
<script>
function test3(){
const area = document.querySelector("#area1");
let count = 0;
// area.innerHTML = `<h3>${count}</h3>`;
//1초마다 함수를 실행
setInterval(function(){
// area.innerHTML = `<h3>${++count}</h3>`;
area.innerHTML = getNowTimeHHMMSS();
}, 1000);
}
function getNowTimeHHMMSS(){
const now = new Date();
let hour = now.getHours(); //시
let min = now.getMinutes(); //분
let sec = now.getSeconds(); //초
const str = `${hour} : ${min} : ${sec}`;
return str;
}
</script>
location
브라우저 주소창과 관련된 객체 -> 현재 문서의 주소(URL) 정보를 가져오거나 변경하여 페이지를 이동할 수 있음.
<button onclick="console.log(location)">실행</button>
<br>
<a href="https://naver.com">네이버이동</a>
<button onclick="location.href='https://naver.com';">네이버로이동</button>
<br><br>
<button onclick="location.assign('https://naver.com');">네이버로이동</button>
<button onclick="location.replace('https://naver.com');">네이버로이동</button>
<!-- replace : 브라우저 히스토리를 저장하지 않음(뒤로가기x) -->
<button onclick="location.href=location.href">새로고침</button>
<button onclick="location.reload()">새로고침</button>
<br><br><br>
<h3>screen객체</h3>
<button onclick="console.log(screen)">객체확인</button>
<h3>navigator객체</h3>
<button onclick="console.log(navigator)">객체확인</button>
<h3>history객체</h3>
<button onclick="console.log(history)">객체확인</button>
jQuery
기존의 자바크스립트 언어만으로 구현하기에는 복잡했던 구문을 간소화하기 위해 만들어진 JavaScript기반의 라이브러리
즉, JavaScript로 유용한 함수나 내용들을 다른 누군가가 이미 정의해 놓은 것
복잡한 JS구문보다 짧고 쉽게 개발이 가능.
장점
- DOM요소와 관련된 스크립트를 보다 쉽게 구현할 수 있음
- AJAX(비동기통신) 이벤트 처리등을 폭넓게 지원함
- jQuery와 관련된 확장 플러그인, 오픈 API 등을 지원(차트, 슬라이드, 캘린더, 드래그 앤 드롭...)
jQuery라이브러리 연결
jQuery를 포함한 모든 외부자료는 2가지 방법으로 연결할 수 있음.
- jQuery라이브러리 파일을 직접 다운로드한 후 파일경로를 통해서 html에 연결.
- CDN(Content Delivery Network) 방식
파일을 다운로드하여서 저장할 필요 없이 라이브러리를 제공하는 사이트의 url을 제시하여
브라우저에서 html을 로딩할 때 해당 서버에서 다운로드해 사용할 수 있도록 하는 방식.
jQuery구문 작성하기
jquery구문으로 DOM요소를 다루는 구문을 기본적으로 작성할 것이기 때문에 문서상에 요소들이 다 만들어지고 나서 실행되어야 한다.
<script>
//.onload -> 특정 요소가 전부 구성이되었을 때 실행하는 이벤트
window.onload = function(){ // window객체가 구성이 완료되자마자 실행할 코드를 작성
console.log("js로딩 완료");
}
//jquery에서 특정 요소를 선택해오고 싶다면 $('선택자') 메서드를 통해 가능.
//jquery요소로 불러온 document가 준비가 되면 전달하는 함수를 실행
$(document).ready(function(){
console.log("document로딩 완료")
})
$(function(){ //window.onload와 동일하게 동작
console.log("jquery 사용준비");
})
console.log("js실행시점");
/*
function $(el){
if(typeof el === Function){
window.onload = function(){
el();
}
} else if(typeof el === Object){
} else if(typeof el === String){
}
}
*/
</script>
태그 선택자
<p>java</p>
<p>oracle</p>
<p>html</p>
<h5 id="css-box">css</h5>
<h5>javascript</h5>
<h5>jquery</h5>
<button class="btn">1</button>
<button class="btn">2</button>
<button class="btn">3</button>
<button class="btn">4</button>
<button class="btn">5</button>
<ul id="ul-area">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<script>
$(function(){
//document.getElementsByTagName('태그명') : 배열
// const pArr = document.getElementsByTagName('p');
// for(let i=0; i<pArr.length; i++){
// pArr[i].style.color = 'red';
// }
// console.log(pArr);
//document.querySelector('선택자')
//document.querySelectorAll('선택자')
//jquery방식 -> $('선택자')
$('p').css({"color": "red"});
$(".btn").click(function(){
alert('클릭됨');
});
//jquery요소를 변수에 담아 사용하고 싶은 경우 jquery요소인지 쉽게 파악하기위해 네이밍을 $로시작함.
let $ulEl = $("#ul-area");
let ulEl = document.getElementById('ul-area');
setTimeout(function(){
//특정요소를 지우고싶을 때
//$('.btn').remove();
//document.querySelector('.btn').remove(); //js로 한다면 반복을통해 하나씩 제거해줘야함.
//#ul-area의 내부요소를 전부 비우고싶을 때
//document.getElementById('ul-area').innerHTML = "";
$('#ul-area').empty();
},2000);
let h5El = document.querySelector("#css-box");
// $(h5El).css("color", "red"); --하나의 스타일속성만 변경하기를 원할 때는 인자를 2개 넘겨주면 됨
$(h5El).css({
"color": "red",
"font-size": "20px"
}); //여러개의 스타일속서을 한번에 변경하고싶다면 객체로 전달하면 됨.
//요소.이벤트명(이벤트핸들러);
$(h5El).click(function(){
alert('실행');
});
//h5El.innerHTML = "<span>내부 변경 확인</span>";
$(h5El).html("<span>내부 변경 확인</span>");
$(h5El).text("<span>내부 변경 확인</span>");
})
</script>
jquery에서 input
text상자 : <input type="text"> <br>
button 상자 : <input type="button"> <br>
checkbox 상자 : <input type="checkbox"> <br>
file 상자 : <input type="file"> <br>
password 상자 : <input type="password"> <br>
radio 상자 : <input type="radio"> <br>
submit 상자 : <input type="submit"> <br>
color 상자 : <input type="color"> <br>
reset 상자 : <input type="reset"> <br>
<script>
$(function(){
//$("input[type='text']") -> $(":text")
$(":text").css("background", "red").val("빨간상자");
console.log($(":text").val()); //값을 가져올 때
$(":button").css({
width: "100px",
height: "100px"
}).val("큰버튼");
//js에서 속성을 변경하는 표준방법 -> setAttribute();
//document.querySelector('input[type="checkbox"]').checked = true;
//document.querySelector('input[type="checkbox"]').setAttribute("checked", true);
$(":checkbox").attr("checked", true);
$(":radio").attr("checked", true).css({width: "50px", height: "50px"});
$(":submit").click(function(){
alert("제출완료");
})
})
</script>