문서 객체 생성 $('<내용>')
- appendTo / prependTo (영역 안)
$(A).appendTo(B);
=> A를 B 뒤에 추가
$(A).prependTo(B);
=> A를 B 앞에 추가
<script>
$(function(){
$('<h2>남극펭귄</h2>').appendTo('#festival');
//h2 생성 -> festival 영역 안, 끝에 위치
$('<img>').attr({
src:'../images/Penguins.jpg',
width: 500
}).appendTo('#festival');
var content=['화요일','문서객체생성','홈페이지제작'];
for(var i=0;i<content.length;i++){
$('<p></p>').html(content[i]).appendTo('#festival');
}
$('<h1>여름축제</h1>').prependTo('#festival');
});
</script>
</head>
<body>
<h1>문서객체생성</h1>
<div id="festival">
</div>
</body>
- insertBefore / insertAfter (영역 밖)
$(A).insertBefore(B)
=> A를 B의 앞에 추가
$(A).insertAfter(B)
=> A를 B의 뒤에 추가
<script>
$(function(){
$('<h2>남극펭귄</h2>').appendTo('#festival');
$('<img>').attr({
src:'../images/Penguins.jpg',
width: 500
}).appendTo('#festival');
var content=['화요일','문서객체생성','홈페이지제작'];
for(var i=0;i<content.length;i++){
$('<p></p>').html(content[i]).appendTo('#festival');
}
$('<h1>여름축제</h1>').prependTo('#festival');
$('<h2>나는 어디에</h2>').insertBefore('#festival');
$('<h2>외톨이</h2>').insertBefore('body'); //사용 지양
});
</script>
</head>
<body>
<h1>문서객체생성</h1>
<div id="festival">
</div>
</body>
- 선택자 활용 - append, prepend, after, before
$(A).append(B); => B를 A 뒤에 추가
$(A).prepend(B); => B를 A 앞에 추가
$(A).after(B); => B를 A 뒤에 추가
$(A).before(B); => B를 A 앞에 추가
A: 선택자 B: 생성
cf) ~To/insert~ => A: 생성 B: 선택자
<script>
$(function(){
var title='<h1>여름축제</h1>';
var sub='<p>이번 축제는~~</p>'
$('#festival').append(title,sub); //festival 영역 안에 title, sub 순차 추가
});
</script>
</head>
<body>
<h1>문서객체생성</h1>
<div id="festival">
<p>축제 내용</p>
</div>
<div id="address">
<h1>주소록 관리</h1>
<div></div>
<div></div>
<div></div>
</div>
</body>
<script>
$(function(){
var title='<h1>여름축제</h1>';
var sub='<p>이번 축제는~~</p>'
$('#festival').append(title,sub);
var content=[
{name:'김철수', address: '서울시 종로구'},
{name:'이영희', address: '서울시 서초구'},
{name:'홍길동', address: '서울시 중구'}
];
$('#address>div').append(function(index){
//return content[index].name+" "+content[index].address;
var item=content[index];
var output='';
output+='<h2>'+item.name+ '</h2>';
output+='<p>'+item.address+'</p>';
return output;
});
$('#address>div').css({
border: '1px solid blue',
'margin-bottom': '10px'
});
});
</script>
</head>
<body>
<h1>문서객체생성</h1>
<div id="festival">
<p>축제 내용</p>
</div>
<div id="address">
<h1>주소록 관리</h1>
<div></div>
<div></div>
<div></div>
</div>
</body>
문서 객체 이동
<script>
$(function(){
$('#images>img').css('width',250);
setInterval(function(){
$('#images>img').first().appendTo('#images');
},2000);
});
</script>
</head>
<body>
<h1>문서 객체 이동</h1>
<div id="images">
<img src="../images/Koala.jpg" alt="">
<img src="../images/Tulips.jpg" alt="">
<img src="../images/Lighthouse.jpg" alt="">
<img src="../images/Penguins.jpg" alt="">
<img src="../images/Jellyfish.jpg" alt="">
</div>
</body>
- clone
<script>
$(function(){
//$('div').append($('h1'));
$('div').append($('h1').clone()); //h1 태그 복제해서 div 내부에 붙임
});
</script>
</head>
<body>
<h1>문서 객체 이동</h1>
<hr>
<div></div>
<hr>
</body>
이벤트 생성
※ 이벤트 : 객체에 취하는 동작
click
dblclick
mousedown : 마우스 누름
mouseup : 마우스 뗌
mousemove : 객체 위에서 마우스 움직임
mouseenter : 객체 위에 마우스 올림
mouseleave : 객체 밖으로 마우스 빠져나감
mouseover : 마우스 올림
mouseout : 마우스 빠져나옴
- on (동적 이벤트 생성)
=> 여러 이벤트 연결
=> 미래에 존재할 이벤트도 연결 (ex. 역학 추적)
$('h1').on(이벤트이름, 함수);
$('h1').on({이벤트이름:함수, 이벤트이름:함수, 이벤트이름:함수});
- 문제 : 클릭시 html 별 추가
<script>
$(function(){
$('h1').on('click',function(){
//클릭이 발생하면 해당 객체의 문자열을 변경
$(this).html(function(index, html){
return html+"*"; //별은 html에 추가되므로 계속 누적
//$(this).html($(this).html()+'*');
});
});
});
</script>
</head>
<body>
<h1>김철수-</h1>
<h1>이영희-</h1>
</body>
- 문제 : hover 시 배경, 글자색 변경 기능 추가
<style>
.reverse{
background-color: black;
color: white;
}
</style>
<script>
$(function(){
$('h1').on({
mouseenter:function(){ //hover 메소드: mouseenter, mouseleave 두 이벤트 가짐
$(this).addClass('reverse');
},
mouseleave:function(){
$(this).removeClass('reverse');
},
click:function(){
$(this).html(function(index, html){
return html+"*";
});
}
});
});
</script>
</head>
<body>
<h1>김철수-</h1>
<h1>이영희-</h1>
</body>
이벤트 제거
- off : 이벤트 제거 메소드
조건 부여하여 원하는 만큼 이벤트 실행 후 제거
<script>
$(function(){
$('h1').on('click', function(){
alert('이벤트 발생');
$(this).off();
})
});
</script>
</head>
<body>
<h1>나를 클릭해보세요</h1>
<h1>나도 클릭</h1>
</body>
- one : 이벤트 한번만 생성
<script>
$(function(){
$('h1').one('click', function(){
alert('이벤트 발생');
})
});
</script>
</head>
<body>
<h1>나를 클릭해보세요</h1>
<h1>나도 클릭</h1>
</body>
- 문제 : 특가 => 냉장고 3, 청소기 5, 에어컨 2대 (배열 활용)
각 h1 클릭 시 1. 알림창으로 '구입해주셔서 고맙습니다' 2. '서둘러주세요. 이제 00대 남았습니다.' (마지막 수량 : '완판되었습니다' )
마지막 수량 완판 시 1. 해당 텍스트: '에어컨 완판!' 2. 글자색 회색
<script>
$(function(){
var count=[3,5,2];
var item=['냉장고', '청소기', '에어컨'];
$('h1').on('click',function(){
var i=$(this).index();
alert('구입해주셔서 감사합니다');
count[i]--;
if (count[i]>0){
alert('이제 '+count[i]+'대 남았습니다');
} else {
alert('완판되었습니다');
$(this).off();
$(this).html(item[i]+' 완판!');
$(this).css('color','gray');
$(this).css('cursor','default');
}
});
});
</script>
</head>
<body>
<h1>냉장고 판매중</h1>
<h1>청소기 판매중</h1>
<h1>에어컨 판매중</h1>
</body>
- 캔버스 예제
<style>
#canvas{
border: 3px solid black;
margin-top: 10px;
}
</style>
<script>
$(function(){
var can=document.querySelector('#canvas');
var context=can.getContext('2d');
var position,x,y;
var sw=false;
var lineWidth=1;
var color='#fff';
$('select').change(function(){
lineWidth=$('select>option:selected').val();
});
$('.colorChange').change(function(){
color=$(this).val();
});
$(can).on({ //can에 이벤트 연결
mousedown:function(event){
//console.log('캔버스 위에서 마우스를 누름');
sw=true;
position=$(this).offset(); //현재 캔버스 위치 좌표값
x=event.pageX-position.left;
y=event.pageY-position.top;
context.beginPath(); //선긋기 준비
context.moveTo(x,y);
},
mousemove:function(){
//console.log('캔버스 위에서 돌아다님');
if(sw==true){
position=$(this).offset();
x=event.pageX-position.left;
y=event.pageY-position.top;
context.strokeStyle=color; //붓 색상
context.lineWidth=lineWidth; //붓 두께
context.lineTo(x,y); //선 긋기
context.stroke();
}
},
mouseup:function(){
//console.log('캔버스 위에서 마우스를 뗌');
sw=false;
}
});
});
</script>
</head>
<body>
<div>
<strong>** 낙서장 **</strong>
<span>붓의 두께</span>
<select name="" id="">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
<span>붓의 색상</span>
<input type="color" class="colorChange">
</div>
<canvas id="canvas" width="800" height="500"></canvas>
</body>