[JqueryMobile] - Select 참조문서

Jquery & Mobile 2011. 9. 19. 15:10
반응형
출처 : http://ebooks.epog.co.kr/jqueryDoc.txt
--jQuery-- 1. 문서 연결 jQuery(document).ready(function() { ..... }); => jQuery(function() { ...... }); 2. 선택자 2.1 CSS 선택자를 이용 * => 모든 엘리먼트 .C .I E => 태그명이 E인 모든 엘리먼트 E F => 태그명이 E인 엘리먼트의 자손중 태그명이 F인 모든 엘리먼트 E>F => 태그명이 E인 엘리먼트의 모든 자식 엘리먼트(자손이 아니다) E+F => 태그명이 E인 엘리먼트의 바로 밑 동생중 태그명이 F인 모든 엘리먼트 E~F => 태그명이 E인 엘리먼트의 동생중 태그명이 F인 모든 엘리먼트 E.C => C 클래스를 가진 태그명이 E인 모든 엘리먼트 E#I => I 아이디를 가진 태그명이 E인 모든 엘리먼트 E[A] => 값 상관없이 A 어트리뷰트를 가진 태그명이 E 인 모든 엘리먼트 E[A=V] => A 어트리뷰트에 V 값을 가진 태그명이 E 인 모든 엘리먼트 E[A^=V] => A 어트리뷰트에 V로 시작되는 값을 가진 태그명이 E 인 모든 엘리먼트 E[A$=V] => A 어트리뷰트에 V로 끝나는 값을 가진 태그명이 E 인 모든 엘리먼트 E[A!=V] => A 어트리뷰트에 V값을 가지지 않거나 A 어트리뷰는가 없는 태그명이 E 인 모든 엘리먼트 E[A*=V] => A 어트리뷰트에 V 값을 포함하고있는 태그명이 E 인 모든 엘리먼트 2.2 위치 선택자 :first => 찾은 요소 중에 첫번째를 찾는 선택자. ex) li a:first => li의 자손중 첫번째 a 엘리먼트 :last => 찾은 요소 중에 마지막을 찾는 선택자. ex) li a:last => li의 자손중 마지막 a 엘리먼트 :first-child => 맏이 선택자. ex) li:first-child => li 중 맏이인 엘리먼트 :last-child => 막내 선택자. ex) li:last-child => li 중 막내인 엘리먼트 :only-child => 독자 선택자 즉 형제가(sibling)없는 엘리먼트 **번째는 1 부터 , 인덱스는 0부터 :nth-child(n) => 형제중 n번째 ex) li:nth-child(2) => 각 목록중 두번째 li :nth-child(even|odd) => 형제중 짝수 또는 홀수 번째 ex) li:nth-child( even) => 각 목록에서 짝수번째 li :nth-child(Xn+Y) => n이 0부터 1씩 증가 하면서 계산된 번째 엘리먼트 :even => 문맥(context)에서 짝수 인덱스(0 부터 계산) :odd => 문맥(context)에서 홀수 인덱스(0 부터 계산) :eq(n) => 문맥(context)에서 n 번 인덱스 :gt(n) => 문맥(context)에서 n 번 인덱스 이후 :lt(n) => 문맥(context)에서 n 번 인덱스 이전 2.3 CSS 와 일반적인 jQuery filter 선택자 :animated => 에니메이션 제어하에 있는 엘리먼트 :button => 폼의 버튼 요소 (input[type=submit],input[type=reset], input[type=button], or button). :checkbox => 폼의 체크박스 요소 :checked => 체크박스와 레이오버튼이 체킹된 상태 :contains(food) => food라는 텍스트를 가진 엘리먼트 :disabled => disabled 가 되어있는 폼 엘리먼트 :enabled => disabled 가 되어있지 않은 폼 엘리먼트 :file => 파일 컨트롤 폼 엘리먼트 :has(selector) => selector 를 가지고 있는 엘리먼트 :header => <h1> ~ <h6> :hidden => form hidden 엘리먼트 :image => type image 엘리먼트. :input => form elements (input, select, textarea,button). :not(selector) => 해당 selector 가 아닌것 :parent => 부모인것 즉 자식을 가지고 있는 엘리먼트 :password => input[type=password]. :radio => input[type=radio]. :reset =>input[type=reset] or button[type=reset]. :selected => 선택되어있는 option 엘리먼트 :submit => button[type=submit] or input[type=submit]. :text => input[type=text]. :visible => visable 엘리먼트. ex) :checkbox:checked:enabled div:has(span) $('tr:has(img[src$="puppy.png"])') 2.4 selector context => $(selector,context) 기본적으로 선택자는 도큐먼트 루트 부터 전체 DOM을 검색한다. 그러나 두번째 인자가 컨텍스트로 주어질 수 있다. 예를 들어 다음과 같은경우 $('div.foo').click(function() { $('span', this).addClass('bar'); }); $('span',this) 에서 span 엘리먼트를 this 컨텍스트 안에서 검색한다. 내부적으로 selector contetxt는 find() 메써드를 구현하고 있다. 그래서 $('span',this) 는 $(this).find('span')과 같은 의미이다. 2.5 html 생성시 두번째 인자는 3.HTML 생성 예제 부분을 보라. 3. HTML 생성 ex) 엘리먼트 생성 css 적용후 body에 참여시키기 $('<img>', { src: 'images/little.bear.png', alt: 'Little Bear', title:'I woof in your general direction', click: function(){ alert($(this).attr('title')); } }) .css({ cursor: 'pointer', border: '1px solid black', padding: '12px 12px 20px 12px', backgroundColor: 'white' }) .appendTo('body'); 4. jquery 래퍼객체 조작 4.1 jquery 래퍼 객체의 크기 4.1.1 size() 4.2 jquery 요소객체에서 특정요소 얻어내기 4.2.1 배열 형식으로 가져오기 : 래퍼 객체가 아닌 코어 객체 반환 - var imgElement=$('img')[0] 4.2.2 get()메써드 를 이용 index 로 가져오기 - get(index) : 래퍼 객체가 아닌 코어 객체 반환 => var imgElement=$('img').get(0); var imgElement=$('img').get(-1); // 끝 요소 4.2.3 래퍼객체 가져오기 - eq() 메써드 를 이용 index 로 가져오기 => eq(index) : 코어가 아닌 래퍼객체 반환 - first() - last() 4.2.4 코어객체를 원소로 가지고있는 배열로 가져오기 - toArray() 4.2.5 엘리먼트의 인덱스 가져오기 - index(element) => 래퍼셋객체에서 인자 엘리먼트의 인덱스 가져온다. element로는 코어객체또는 래퍼객체를 사용할수있다. 래퍼 객체인경우 맏이의 인덱스 번호를 가져온다. 또한 index() 메써드가 인자 없이 쓰일 경우는 해당 래퍼객체의 부모노드기준 인덱스 가져온다. 4.2.6 래퍼객체를 자르거나 증가시기키 - add() =>래퍼 객체에 엘리먼트 추가하여 새로운 래퍼객체 반환: http://api.jquery.com/add/ add(selector) , add(elements) , add( html ), add(selector,context) ex) $('p').addClass('apple').add('div').addClass('banana') => p 요소에는 apple클래스 banana 클래스 적용 div 요소에는 banana 클래스만 적용 - not() => 래퍼 객체에서 특정 엘리먼트 제거하여 새로운 래퍼객체 반환 : http://api.jquery.com/not/ not(selector),not(elements),not(function(index)) ex) => 홀수 인덱스 li 제외 $('li').not(function(idx) { if(idx%2) { return idx; } }).css('background-color','red'); - filter() .filter( selector ) 선택자에 매치 version added: 1.0 .filter( function(index) ) => function()은 논리값 반환 ex) $('li').filter(function(index) { return $('strong', this).length == 1; // this 컨텍스트 안에서 }).css('background-color', 'red'); .filter( element ) 엘리먼트에 매치 version added: 1.4 .filter( jQuery object ) jQuery object An existing jQuery object to match the current set of elements against. version added: 1.4 - slice(begin,end) 해당 포지션에 맞는 새로운 래퍼객체 생성후 리턴 - has() => 선택자에 매칭되는 엘리먼트를 가지고 있는 엘리먼트 래퍼 객체 .has( selector ) version added: 1.4. selector : A string containing a selector expression to match elements against. has( contained ) version added: 1.4. contained : A DOM element to match elements against. - map( callback(index, domElement) ) => 현 래퍼객체를 순회하면서 함수를 실행시킨다. 반환값은 래퍼객체이다. 반환값이 래퍼객체이므로 get()을 사용하여 기본배열로 만들어 사용하는것이 일반적이다. - each( function(index, Element) ) 4.2.7 관계를 이용하여 래퍼객체 구하기 - children([selector]) - closest([selector]) =>조상 엘리먼트중 선택자에 매치되는 래퍼 객체 반환 - contents() => 텍스트 노드 까지 포함하여 해당 래퍼객체의 내용 래퍼객체 반환 종종 iframe의 내용을 얻는데 쓰인다. - next([selector]) => 선택자에 매치되는 아래 형제 래퍼객체 반환 - nextAll([selector]) => 선택자에 매치되는 모든 아래 형제 래퍼객체 반환 - nextUntil([selector]) => 선택자에 매치되는 아래형제 전까지의 모든 아래 형제 반환 - offsetParent() => 오프셋 페어런트 - parent([selector]) => 부모 - parents([selector]) => 도큐먼트 루트를 제외한 모든 부모 - parentsUntil([selector]) => 매치 엘리먼트 전까지 모든 부모 - prev([selector]) => 바로 위 형 엘리먼트 래퍼 객체 - prevAll([selector]) => 모든 형 엘리먼트 래퍼 객체 - prevUntil([selector]) => 매치 엘리먼트 전까지의 모든 형 엘리먼트 래퍼 객체 - siblings([selector]) => 모든 형제 엘리먼트 래퍼 객체 4.2.8 기타 - find( selector ) => 선택자에 매치되는 래퍼객체 반환 - is( selector ) => 래퍼객체에 선택자에 하나라도 매치되면 true 아니면 false 4.2.9 래퍼객체 다루기 - end() => 제이쿼리 메써드 체인에서 이전 체인 래퍼 객체 반환 - andSelf() => 제이쿼리 메써드 체인에서 두개의 이전 래퍼 객체 병합 반환 5. 제이쿼리를 이용 웹문서을 살아있게 만들기 *이번장은 다음과 같은 것을 다룬다. . 엘리먼트에 속성 다루기 . 엘리먼트에 일반 데이타 저장하기 . 엘리먼트에 클래스명 조작하기 . DOM 엘리먼트에 내용 넣기 . 엘리먼트에 일반 데이타 저장하고 꺼내오기 . 폼 엘리먼트에 값 셋팅 및 가져오기 . 추가,옮기기,교체를 통하여 DOM 트리 수정하기 5.1 엘리먼트의 속성 조작하기 5.1.1 attr( attributeName ) Returns: String 5.1.2 attr( attributeName, value ) Returns: jQuery - attr( attributeName, value ) - attr( map ) => map은 속성-값 셋 - attr( attributeName, function(index, attr) ) ex) $('#greatphoto').attr('alt', 'Beijing Brush Seller'); $('#greatphoto').attr({ alt: 'Beijing Brush Seller', title: 'photo by Kelly Clark' }); $('ul > li').attr('class',function(idx,attr) { return attr+idx; }) ** jQuery normalized name : DOM name ** cellspacing : cellSpacing class : className colspan : colSpan cssFloat : styleFloat for IE, cssFloat for others float : styleFloat for IE, cssFloat for others for htmlFor frameborder : frameBorder maxlength : maxLength readonly : readOnly rowspan : rowSpan styleFloat : styleFloat for IE, cssFloat for others tabindex : tabIndex usemap : useMap 5.1.3 .removeAttr( attributeName ) Returns: jQuery 5.2 엘리먼트에 일반 데이터 저장하기 5.2.1 data( key, value ) Returns: jQuery - data( key, value ) - data( obj ) ex) $('div').data('color','red').data('fruits','apple'); $('div span:first').text($('div').data('color')); $('div span:last').text($('div').data('fruits')); 5.2.2 data( key ) Returns: Object - data( key ) - data() 5.2.3 removeData( [ name ] ) Returns: jQuery ex) $("div").removeData("test1"); 5.3 클래스 조작하기 5.3.1 addClass( className ) Returns: jQuery - addClass( className ) - addClass( function(index, class) ) ex) $('ul li:last').addClass(function() { return 'item-' + $(this).index(); }); $("p:last").addClass("selected highlight"); $('div').addClass(function(i,class) { if ( i === 1 ) { $('p').text('There is one green div'); class += ' green'; } return class; }); 5.3.2 removeClass( [ className ] ) Returns: jQuery - removeClass( [ className ] ) - removeClass( function(index, class) ) ex) $("p:even").removeClass("blue"); $("p:odd").removeClass("blue under"); $("p:eq(1)").removeClass(); // 모든 클래스 $('li:last').removeClass(function() { return $(this).prev().attr('class');//제거될 클래스명 리턴 }); 5.3.3 toggleClass( className ) Returns: jQuery - toggleClass( className ) - toggleClass( className, switch ) className : 하나나 그이상의 토글될 클래스명 switch : 클래스가 추가될것인지 제거 될것인지를 결정하는 불리언 값 - toggleClass( function(index, class), [ switch ] ) ex) $('div.foo').toggleClass(function() { if ($(this).parent().is('.bar')) { return 'happy'; } else { return 'sad'; } }); $("p").each(function() { var $thisParagraph = $(this); var count = 0; $thisParagraph.click(function() { count++; $thisParagraph.find("span").text('clicks: ' + count); $thisParagraph.toggleClass("highlight", count % 3 == 0); }); }); 5.4 스타일 조작 5.4.1 css( propertyName ) Returns: String => ie에서는 동작 안할수도 있음 5.4.2 css( propertyName, value ) Returns: jQuery - css( propertyName, value ) - css( propertyName, function(index, value) ) - css( map ) 5.4.3 width() , height() - width() Returns: Integer - width( value ) Returns: jQuery - width( function(index, width) ) - height() Returns: Integer - height( value ) Returns: jQuery - height( function(index, width) ) 5.4.4 innerWidth(),innerHeight() => 패딩까지 포함한 길이 값(정수) 반환 5.4.5 outerWidth( [ includeMargin ] ) , outerHeight( [ includeMargin ] )=> 보더까지 포함한 길이 값(정수) 반환 - includeMargin : 불리언 값으로 마진까지 포함할 것인가. 5.4.6 offset() => 래퍼객체의 첫번째 엘리먼트의 문서내에서의 좌표를 반환한다. position() 메써드는 오프셋 페어런트로부터의 상대적인 좌표를 반환한다. 보더,패딩,마진을 고려한 좌표를 얻는 방법은 jQuery에 존재하지 않는다. - offset() Returns: Object - offset( coordinates ) - offset( function(index, coords) ) ex) $("*", document.body).click(function (e) { var offset = $(this).offset(); e.stopPropagation(); $("#result").text(this.tagName + " coords ( " + offset.left + ", " + offset.top + " )"); }); 5.4.7 .position() Returns: Object => 읽기만 가능 5.4.8 스크롤 제어 - scrollLeft() - scrollLeft(value) - scrollTop() - scrollTop(value) => value : 픽셀 정수값 5.5 html() => xml 문서에서는 사용불가능 5.5.1 html() Returns: String 5.5.2 html( htmlString ) Returns: jQuery - html( htmlString ) - html( function(index, oldhtml) ) ex) jQuery(function() { $( 'div' ).html( function(idx,ohtml) { console.log(idx+ohtml); return '<b>test</b>'; }); }); 5.6 text() 5.6.1 text() Returns: String 5.6.2 text( textString ) Returns: jQuery - text( textString ) - text( function(index, text) ) ex) $('div.demo-container').text('<p>This is a test.</p>') 이코드는 다음과 같은 코드를 만든다. <div class="demo-container"> &lt;p&gt;This is a test.&lt;/p&gt; </div> 5.7 엘리먼트 옮기기,복사하기.... 5.7.1 append() - 자식요소로 맨끝부분에 추가 - append( content, [ content,... ] ) Returns: jQuery => content : DOM 엘리먼트,HTML 또는 래퍼 객체 가 끝 부분에 추가된다. ex) var $newdiv1 = $('<div id="object1"/>'); var newdiv2 = document.createElement('div'); var existingdiv1 = document.getElementById('foo'); $('body').append($newdiv1, [newdiv2, existingdiv1]); - append( function(index, html) ) => 함수에서는 각 엘리먼트 안의 끝에 추가될 html 스트링을 리턴해 주면된다. index는 각 엘리먼트 인덱스값,html은 기존 html 스트링을 받는다. 5.7.2 prepend()- 자식요소로 맨앞부분에 추가 - prepend( content, [ content,... ] ) Returns: jQuery => content : DOM 엘리먼트,HTML 또는 래퍼 객체 가 앞 부분에 추가된다. ex) var $newdiv1 = $('<div id="object1"/>'); var newdiv2 = document.createElement('div'); var existingdiv1 = document.getElementById('foo'); $('body').prepend($newdiv1, [newdiv2, existingdiv1]); - prepend( function(index, html) ) => 함수에서는 각 엘리먼트 안의 앞에 추가될 html 스트링을 리턴해 주면된다. index는 각 엘리먼트 인덱스값,html은 기존 html 스트링을 받는다. 5.7.3 before() - before(content ,[content,..]) Returns: jQuery => 전달된 html 프래그먼트나 엘리먼트를 대상 엘리먼트의 바로위 형제로 넣는다. ex1) $('.inner').before('<p>Test</p>'); $('.container').before($('h2')); $("<div/>").before("<p></p>"); => DOM 트리에 참여하고 있지않은 경우(1.4 버전부터 지원) ex2) var $newdiv1 = $('<div id="object1"/>'); var newdiv2 = document.createElement('div'); var existingdiv1 = document.getElementById('foo'); $('p').first().before($newdiv1, [newdiv2, existingdiv1]); <h1>jquery</h1> <p>p1</p> <p>p2</p> <p>p3</p> <div id="foo">foo</div> => <h1>jquery</h1> <div id="object1"></div> <div></div> <div id="foo">foo</div> <p>p1</p> <p>p2</p> <p>p3</p> - before( function ) => 함수에서는 이전 형제로 추가될 html 문자열을 리턴해주면 된다. 5.7.4 after() => 바로 아래 동생으로 추가해주는것을 제외하고는 before() 와 동일 5.7.5 appendTo() - appendTo( target ) => 타겟의 끝 부분에(막내) 해당 래퍼객체 추가 ex) $( '<a href="#">daum</a>').appendTo( $('p') ); // 모든 p 엘리먼트에 link 추가 5.7.6 prependTo() - prependTo( target ) => 타겟의 처음 부분에(맏이) 해당 래퍼객체 추가 5.7.7 insertBefore() / insertAfter () - insertBefore( target ) - insertAfter(target) => before() 나 after() 와 동일한 기능을 수행한다. 차이점은 새롭게 추가되는 엘리먼트의 문법상 위치이다. 아래 예제의 .inner 위치를 보라 $('.inner').before('<p>Test</p>'); => inner 클래스를 가진 모든 엘리먼트의 바로 위 형으로 문단 엘리먼트가 추가된다. ('<p>Test</p>').insertBefore('.inner') => inner 클래스를 가진 모든 엘리먼트의 바로 위 형으로 문단 엘리먼트가 추가된다. 5.7.8 wrap() : 래퍼객체 각 엘리먼트를 감싸준다. - wrap( wrappingElement ) : 래퍼객체 각 엘리먼트를 감싸준다. => wrappingElement : html 조각,선택자 표현,래퍼객체,DOM 객체 - wrap( wrappingFunction ) ex) a 엘리먼트중 apple 클래스를 가지고 있는 것만 div 로 감싸기 $( $('div#foo > a')).wrap(function() { if($(this).hasClass('apple')) { return '<div class="wrap" />'; } }) 5.7.9 wrapAll() : 래퍼객체 전체를 감싸준다. - wrapAll( wrappingElement ) => wrappingElement : html 조각,선택자 표현,래퍼객체,DOM 객체 ex) <div id="foo"> <a href="#" class="apple">foo</a> <span>bar</span> <a href="#" class="apple">coo</a> <a href="#" class="apple">poo</a> <span>too</span> </div> => $( $('div#foo > span')).wrapAll('<div class="wrap" />'); wrap() 메써드 와의 차이점 주의 <div id="foo"> <a href="#" class="apple">foo</a> <div class="wrap"> <span>bar</span> <span>too</span> </div> <a href="#" class="apple">coo</a> <a href="#" class="apple">poo</a> </div> 5.7.10 wrapInner() : 래퍼객체의 각 엘리먼트 안을 싸준다. - wrapInner( wrappingElement ) Returns: jQuery - wrapInner( wrappingFunction ) Returns: jQuery ex) <div id="foo"> <a href="#" class="apple">foo</a> <span>bar</span> <a href="#" class="apple">coo</a> <a href="#" class="apple">poo</a> <span>too</span> </div> => $( $('div#foo > span')).wrapInner('<strong class="wrap" />'); <div id="foo"> <a href="#" class="apple">foo</a> <span><strong class="wrap">bar</strong></span> <a href="#" class="apple">coo</a> <a href="#" class="apple">poo</a> <span><strong class="wrap">too</strong></span> </div> 5.7.11 unwrap() 예제로 대체 ex) 버튼을 누르면 쌋다 벗겼다 한다. $("button").toggle(function(){ $("p").wrap("<div></div>"); }, function(){ $("p").unwrap(); }); 5.7.12 remove( [ selector ] ) Returns: jQuery => DOM 에서 매칭되는 엘리먼트를 제거한다. ex) ##원본 <div id="foo"> <a href="#" class="apple">foo</a> <span>bar</span> <a href="#" >coo</a> <a href="#" >poo</a> <span>too</span> </div> => $('a').remove(); <div id="foo"> <span>bar</span> <span>too</span> </div> or => $('a').remove('.apple'); <div id="foo"> <span>bar</span> <a href="#">coo</a> <a href="#">poo</a> <span>too</span> </div> 5.7.13 detach( [ selector ] ) Returns: jQuery => DOM 에서 매치되는 엘리먼트 제거 remove()와의 차이점은 제거되는 엘리먼트 래퍼객체 반환 selector 사용시 반환 래퍼객체는 selector없이 사용되었을때의 래퍼 객체 반환, 버그 같음 5.7.14 empty() Returns: jQuery -empty() => 래퍼셋객체를 비워줌 ex) $( '#foo' ).empty() 5.7.15 clone( [ withDataAndEvents ] ) Returns: jQuery => deep copy - clone( [ withDataAndEvents ] ) withDataAndEvents : 이벤트와 데이타(data() 메서드를 사용하여 데이타 저장한것) 까지 복제할것인가 불리언값 - clone( [ withDataAndEvents ], [ deepWithDataAndEvents ] ) 5.7.16 replaceWith( newContent ) Returns: jQuery => A.replace(B) A를 B로 교체 - replaceWith( newContent ) - replaceWith( function ) ex) $('.inner').replaceWith('<h2>New heading</h2>'); ('.third').replaceWith($('.first')); 5.7.17 replaceAll( target ) Returns: jQuery => A.replaceAll(B) A로 B를 교체 ex) $('<h2>New heading</h2>').replaceAll('.inner'); $('.first').replaceAll('.third'); => .first 클래스를 가진 엘리먼트가 .third 클래스를 가진 엘리먼트로 교체된다. 5.8 폼 엘리먼트의 값 다루기 5.8.1 val() - val() Returns: String, Array - val( value ) Returns: jQuery - val( function(index, value) ) ex) $("button").click(function () { var text = $(this).text(); $("input").val(text); }); $('input').bind('blur', function() { $(this).val(function(i, val) { return val.toUpperCase(); }); }); ex) <form name="testForm"> <p> <input type="checkbox" name="color" value="red" /> <input type="checkbox" name="color" value="blue" /> <input type="checkbox" name="color" value="yellow" /> </p> <p> <input type="radio" name="favor" value="pizza" /> <input type="radio" name="favor" value="cola" /> <input type="radio" name="favor" value="pasta" /> </p> <p> <select name="keyfield"> <option value="userName">이름</option> <option value="subject">제목</option> <option value="contents">내용</option> </select> </p> <p> <select name="fruits" multiple="multiple"> <option value="apple">사과</option> <option value="banana" selected="selected">바나나</option> <option value="grape">포도</option> <option value="orange">오렌지</option> <option value="blueberry" selected="selected">블루베리</option> </select> </p> </form> => console.log( $( 'input[type=checkbox]' ).val() ); // red console.log( $( 'select[name=keyfield]' ).val() ); // userName console.log( $( 'input' ).val() ); //red console.log( $( 'select[name=fruits]' ).val() ); // [banana,blueberry] $( 'input[type=checkbox]' ).val(['blue']); // blue값을 가진 체그박스 체크 $( 'input[type=radio]' ).val(['pasta']); // pasta 값을 가진 레디오버튼 체크 $( 'select[name=keyfield]' ).val(['subject']); // subject 값을 가진 옵션 선택 6. 이벤트 ** 이 장은 다음과같은 주제를 다룬다. - 브라우저에의해 구현되는 이벤트 모델 - 제이쿼리 이벤트 모델 - DOM 엘리먼트에 이벤트핸들러 묶기 - 이벤트 객체의 인스턴스 - 자바스크립트을 이용한 이벤트 처리 시작하기 - 선행 이벤트처리기 등록하기 6.1 제이쿼리 이벤트 모델 - 이벤트 핸들러를 등록하는데 통일된 방법 제공 - 각 엘리먼트에 복수의 이벤트핸들러 허용 - 표준 이벤트명 사용 - 이벤트핸들러의 파라미터로 이벤트 인스턴스를 가능하도록 만들어 줌 - 이벤트 취소 블록킹의 통일된 방법 제공 6.1.1 bind() - bind( eventType, [ eventData ], handler(eventObject) ) Returns: jQuery -- eventType : 이벤트 타입명 -- eventData : 이벤트 핸들러로 전달될 데이터 맵 -- handler(eventObject) : 이벤트가 발생하였을때마다 실행할 함수 - bind( eventType, [ eventData ], false ) -- false : 이벤트 버블링 금지 및 기본 행동 취소 - bind( events ) -- events : 맵 데이터 ** 숏컷 메써드 : bind('click',.. ) => click(...) blur, focus, focusin, focusout, load, resize, scroll, unload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error ex) - 기본 사용법 $('#foo').bind('click', function() { alert('User clicked on "foo."'); }); - 복수 이벤트 $('#foo').bind('mouseenter mouseleave', function() { $(this).toggleClass('entered'); }); - 이벤트 핸들러 $('#foo').bind('click', function() { alert($(this).text()); }); function test(){ alert("Hello"); } $("button").click( test ); $("button").click( test ); => 경고창 두번 뜬다. - 이벤트핸들러에서 false를 반환하면 이벤트 객체에 .preventDefault() 와 .stopPropagation() 를 호출한 것과 동일하다. - 데이타 넘기기 var message = 'Spoon!'; $('#foo').bind('click', {msg: message}, function(event) { alert(event.data.msg); }); message = 'Not in the face!'; $('#bar').bind('click', {msg: message}, function(event) { alert(event.data.msg); }); - 기본행동과 이벤트 버블링 중지 $("form").bind("submit", function() { return false; }) - 기본행동 중지 $("form").bind("submit", function(event) { event.preventDefault(); }); - 이벤트 버블링 중지 $("form").bind("submit", function(event) { event.stopPropagation(); }); - 커스텀 이벤트 예제 jQuery(function() { $("p").bind("myCustomEvent", function(e, myName, myValue){ $(this).text(myName + ", hi there!"); $("span").stop().css("opacity", 1) .text("myName = " + myName) .fadeIn(30).fadeOut(1000); }); $("button").click(function () { $("p").trigger("myCustomEvent", [ "John" ]); }); }); - 복수 이벤트 $("div.test").bind({ click: function(){ $(this).addClass("active"); }, mouseenter: function(){ $(this).addClass("inside"); }, mouseleave: function(){ $(this).removeClass("inside"); } }); 6.1.2 one() - one( eventType, [ eventData ], handler(eventObject) ) Returns: jQuery : 단 한번만 이벤트 처리 6.1.3 unbind() : 이벤트 핸들러 제거 - unbind( [ eventType ], [ handler(eventObject) ] ) Returns: jQuery ex) - 모든 핸들러 제거 $('#foo').unbind(); - 특정 이벤트 핸들러 제거 ('#foo').unbind('click'); - 특정 이벤트 특정 핸들러 제거 var handler = function() { alert('The quick brown fox jumps over the lazy dog.'); }; $('#foo').bind('click', handler); $('#foo').unbind('click', handler); - 네임스페이스 사용 ex) <p id="btnGroup"> <button id="b1" type="button">버튼1</button> <button id="b2" type="button">버튼2</button> <button id="b3" type="button">버튼3</button> <button id="b4" type="button">버튼4</button> </p> => $( '#b1' ).bind('click.myEvt1',myFunc); $( '#b2' ).bind('click.myEvt2',myFunc); $( '#b3' ).bind('click.myEvt3',myFunc); $( '#b4' ).bind('click.myEvt4',myFunc); $( 'button' ).unbind('click.myEvt3'); // 버튼3 이벤트 핸들러만 제거 됨 - 이벤트 오브젝트 사용 ex) var timesClicked = 0; $('#foo').bind('click', function(event) { alert('The quick brown fox jumps over the lazy dog.'); timesClicked++; if (timesClicked >= 3) { $(this).unbind(event); // 이벤트 오브젝트 사용 } }); 6.1.4 브라우저에 독립적인 제이쿼리 이벤트 객체 프로퍼티/메써드 - altKey : 이벤트가 발생하였을때 altKey가 눌려 있느냐 여부 불리언값. - ctrlKey : 이벤트가 발생하였을때 ctrlKey가 눌려 있느냐 여부 불리언값. - currentTarget : 버블링되는동안 이벤트를 실제 처리하고 있는 엘리먼트. - data : bind() 메써드의 두번째 인자로 전달된 데이터 - metaKey : 이벤트가 발생하였을때 metaKey가 눌려 있느냐 여부 불리언값. pc->ctrl key ,mac->command key - pageX : 마우스 이벤트에 있어서 페이지에서의 수평 좌표 - pageY : 마우스 이벤트에 있어서 페이지에서의 수직 좌표 - relatedTarget : 마우스 이동 메써드에서의 - screenX : 마우스 이벤트에 있어서 스크린에서의 수평 좌표 - screenY : 마우스 이벤트에 있어서 스크린에서의 수직 좌표 - shiftKey : 이벤트가 발생하였을때 shiftKey가 눌려 있느냐 여부 불리언값. - result : 바로 이전 이벤트 처리시 반환되었던 값 - target : 이벤트핸들러를 실제 등록시킨 엘리먼트 - timestamp : 제이쿼리 이벤트 객체가 생성된 밀리초단위 타임 스탬프 - type : 이벤트 타입 - which : 키보드 이벤트에 있어서 키 코드값, 마우스이벤트에 있어서 버튼 코드값( left->1,middle->2,right->3) - preventDefault() - stopPropagation() : 추가 되는 이벤트에는 영향을 주지 않는다. - stopImmediatePropagation() : 추가 되는 이벤트에도 영향을 준다. - isDefaultPrevented() - isPropagationStopped() - isImmediatePropagationStopped() 6.1.5 live() <-> die() - live( eventType, handler ) - live( eventType, eventData, handler ) - live( events ) ex) <p id="btnGroup"> <button type="button">버튼1</button> </p> <div id="rstBox"></div> => $( '#btnGroup > button' ).bind('click',myFunc); $( '#btnGroup' ).append('<button type="button">버튼2</button>'); // 이경우 이벤트 핸들러가 등록되지 않는다. => $( '#btnGroup > button' ).live('click',myFunc); $( '#btnGroup' ).append('<button type="button">버튼2</button>'); // 이경우 추가 되는 엘리먼트에도 이벤트 핸들러가 등록된다. 6.1.6 기타 이벤트 기반 메써드 - toggle( handler(eventObject), handler(eventObject), [ handler(eventObject) ] ) => 클릭 이벤트 발생시 순서대로 토글링 - hover() => 언 바인드는 $(' .. ').unbind('mouseenter mouseleave'); -- hover( handlerIn(eventObject), handlerOut(eventObject) ) Returns: jQuery -- hover( handlerInOut(eventObject) ) Returns: jQuery ex) <style type="text/css"> #outer1,#outer2,#outer3 { width:300px; border:4px solid navy; background-color:skyblue; margin:20px; } #inner1,#inner2,#inner3 { height:100px; border:4px solid red; background-color:yellow; margin:20px; } </style> <h1>짜증나는 마우스오버 마우스아웃 이벤트의 행동의 해결 2가지</h1> <div id="outer1"> outer1 짜증 <div id="inner1">inner1</div> </div> <div id="outer2"> outer2 해결1 <div id="inner2">inner2</div> </div> <div id="outer3"> outer3 해결2 <div id="inner2">inner3</div> </div> => function report(evt) { console.log(evt.type+' on '+evt.target.id); } jQuery(function() { $( '#outer1' ).bind('mouseover mouseout',report); $( '#outer2' ).bind('mouseenter mouseleave',report); $( '#outer3' ).hover(report); }); 7. 애니메니션과 이펙트로 페이지에 활력주기 ** 이번 장은 다음과 같은 것을 다룬다. - 애니메이션없이 엘리먼트 보이게하기 감추기 - 코어 애니메니션을 이용 엘리먼트 보이고 감추기 - 커스텀 애니메이션 만들기 - 애니메이션 제어 와 펑션 큐잉 7.1 보이게하기,감추기 : http://115.93.104.42:8080/~class/jquery/module1.html 7.1.1 show() : 크기,불투명도,디스플레이 - show() - show( duration, [ callback ] ) - show( [ duration ], [ easing ], [ callback ] ) 7.1.2 hide() - hide() - hide( duration, [ callback ] ) - hide( [ duration ], [ easing ], [ callback ] ) 7.1.3 toggle() -> 이벤트핸들러에도 같은 이름의 메써드가 있다. - toggle() - toggle( [ duration ], [ callback ] ) - toggle( [ duration ], [ easing ], [ callback ] ) - toggle( showOrHide ) -- duration : 'fast'(200 miliseconds) ,normal(400 miliseconds), 'slow'(600 miliseconds) ,miliseconds -- callback : 동작 완료후 호출될 함수 -- showOrHide : 보이게 할것인가 감출것인가의 불리언값 7.2 엘리먼트 애니메니션하기 : http://115.93.104.42:8080/~class/jquery/module2.html 7.2.1 점진적으로 보이기,감추기 - 7.1의 메써드를 duration과 같이 사용 7.2.2 Fading - fadeIn( [ duration ], [ callback ] ) Returns: jQuery - fadeIn( [ duration ], [ easing ], [ callback ] ) - fadeOut( [ duration ], [ callback ] ) - fadeOut( [ duration ], [ easing ], [ callback ] ) - fadeTo( duration, opacity, [ callback ] ) - fadeTo( duration, opacity, [ easing ], [ callback ] ) -- opacity : 불투명도 ( 0~1 ) - slideDown( [ duration ], [ callback ] ) http://115.93.104.42:8080/~class/jquery/module3.html - slideDown( [ duration ], [ easing ], [ callback ] ) - slideUp( [ duration ], [ callback ] ) - slideUp( [ duration ], [ easing ], [ callback ] ) - slideToggle( [ duration ], [ callback ] ) http://115.93.104.42:8080/~class/jquery/module4.html - slideToggle( [ duration ], [ easing ], [ callback ] ) 7.2.3 애니메이션 정지 - stop( [ clearQueue ], [ jumpToEnd ] ) -- clearQueue : true 값으로 설정되면 현 애니메이션을 중단시킬뿐만 아니가 대기하고 있던 다른 애니메이션도 중단한다. 기본값은 false -- jumpToEnd : true 값으로 설정되면 중단된 애니메이션의 마지막 단계로 상태를 바꾸어 준다. 기본값은 false 7.3 커스텀 애니메이션 만들기 7.3.1 animate() : CSS 속성셋을 이용하여 커스텀 애니메이션 수행 - animate( properties, [ duration ], [ easing ], [ complete ] ) -- properties : CSS Map -- complete : 애니메이션이 완성되면 호출될 함수 - animate( properties, options ) -- properties : CSS Map -- options : 추가 옵션 맵 duration : easing : complete : 애니메이션 완성후 호출될 함수 step : 에니메이션의 각 단계후 호출될 함수 queue : 하나의 애니메이션이 완성된후 잠시 멈출 것인가 불리언값, specialEasing : CSS 프로퍼티와 각 프로퍼티에 해당하는 이징펑션의 맵 - 애니메이션 프로퍼티와 값 -- 모든 애니메이션되는 프로퍼티는 아래 언급되는 것을 제외하고는 하나의 숫자값이어야 한다. -- 대부분의 비 숫자값 프로퍼티는 기본 제이쿼리기능을 사용하여 애니메이션 될 수 없다. (예를 들어 height,width 또는 left 등은 애니메이션 될수 있으나 background-color는 될 수 없다.) -- 프로퍼티 값은 특별히 정해지지 않는한 px값으로 사용한다. em또는 %는 특별히 정해져야한다. -- 스타일 속성뿐만 아니라 scrollTop,scrollLeft 등도 애니메이션 될 수 있다. -- 단축 CSS 속성은 지원 되지않는다. 예를들면 marginLeft,marginTop... 등등으로 사용하여야 한다. -- 숫자값뿐만 아니라 각 프로퍼티는 'show','hide', 'toggle' 값을 가질 수 있다. -- +=,나 -= 를 사용하여 상대적으로 값을 정할 수도 있다. -- slideDown(),fadeIn() 등과 같은 단축 애니메이션 메써드와는 달리 표시속성을 바꾸지는 않는다. - Duration -- slow(600),normal(400),fast(200) ,밀리초단위 - 기본 사용법 ex1) $('div#top').click(function() { $(this).animate({ opacity:0.5, left:'+=50', height:'+=50' },1000,function() { console.log('animation complete!'); }); }); - 스텝펑션 두번째 animate() 메써드는 step 옵션을 제공한다. step 옵션에는 각각의 애니메이션이 완료 되었을때 호출되는 두개의 매개변수(now,fx)를 가지는 콜백 함수를 지정하게 되고, 함수 안의 this는 애니메이션되는 DOM 코어 엘리먼트가 된다. -- now : 애니메이션된 프로퍼티 숫자값 -- fx : jQuery.fx 프로토타입의 참조로서 elem,start,end,first,last,prop 등등의 프로퍼티를 가진다. ex1) $('div#top').click(function() { $(this).animate({ opacity:'-=0.1', left:'+=50', height:'+=50' },{ step:function(now,fx) { $('body').append('<div>'+fx.elem.id+','+fx.prop+':'+now+'</div>'); }, duration:1000 }); }); - 이징 제이쿼리에서 기본적으로 제공하는 이징은 linear,swing 두개뿐이다. 나머지 다양한 이징기능은 제이쿼리유아이에 정의 되어있다. http://jqueryui.com/demos/effect/easing.html ex1) $('#btn').click(function() { $('#top').animate({ width:'toggle', height:'toggle' },1000,'linear',function() { $(this).after('<div>animation complete!</div>'); }); }); ex2) $('#btn').click(function() { $('#top').animate({ width:['toggle','linear'], height:['toggle','swing'], opacity:'toggle' },1000,'swing',function() { $(this).after('<div>animation complete!</div>'); }); }); ex3) $('#btn').click(function() { $('#top').animate({ width:'toggle', height:'toggle' },{ duration:1000, specialEasing: { width:'linear', height:'swing' }, complete:{ $(this).after('<div>animation complete!</div>'); } }); }); ex4) div 떨어뜨리기 예제 $('div').click(function() { $(this) .css('position','relative') .animate( { opacity: 0.1, top: $(window).height() - $(this).height() - $(this).position().top }, 'slow', function(){ //$(this).hide(); } ); }); ex5) div puff(폭발) 예제 $('div').click(function() { var position=$(this).position(); $(this) .css({ position:'absolute', top:position.top, left:position.left }) .animate({ opacity:'hide', width:$(this).width()*5, height:$(this).height()*5, top: position.top - ($(this).height() * 5 / 2), left: position.left - ($(this).width() * 5 / 2) }, 'slow'); }); - 애니메이션과 큐잉(Queuing) -- 다음 코드의 결과를 예상해 보자 $('div').click(function() { console.log(1); $(this).animate({left:'+=256'},3000); console.log(2); $(this).animate({top:'+=256'},3000); console.log(3); }); 제이쿼리는 애니메이션을 큐잉하고 있다가 순서대로 애니메니션을 수행한다. 제이쿼리는 이런 목적을 위해 만들어진 특수 오브젝트인 fx에 각 애니메션되는 엘리먼트를 큐잉한다. -- 실행을 위한 펑션 큐잉 ex) 동일한 큐잉 기능을 수행하는 코드 $('div#box1').click(function() { $(this).animate({left:'+=100'},1000); $(this).animate({top:'+=100'},1000); $(this).animate({left:'-=100'},1000); $(this).animate({top:'-=100'},1000); }); $('div#box2').click(function() { $(this).animate({left:'+=100'},1000,function(){ $(this).animate({top:'+=100'},1000,function(){ $(this).animate({left:'-=100'},1000,function(){ $(this).animate({top:'-=100'},1000); }); }); }); }); => 많이 복잡하다. -- queue( [ queueName ] ) Returns: Array queueName : 큐이름, 기본값은 표준 효과 큐인 fx 이다. : 해당 엘리먼트에 실행될 함수의 큐를 보여준다. -- queue( [ queueName ], newQueue ) Returns: jQuery newQueue : 현 큐 내용을 교체할 함수 배열 : 큐를 조작한다. -- queue( [ queueName ], callback( next ) ) Returns: jQuery callback : 큐에 저장될 새로운 함수, -- dequeue( [ queueName ] ) Returns: jQuery 큐에 저장된 함수를 꺼내와 실행한다.(한 큐씩) ex) 일반 함수 큐잉 <div> <img src="chapter07/earth.png" alt="Earth" /> <img src="chapter07/moon.png" alt="Moon" /> </div> <button type="button" class="green90x24">Dequeue</button> => $('img').queue('chain', function(){ console.log('First: ' + $(this).attr('alt')); }); $('img').queue('chain', function(){ console.log('Second: ' + $(this).attr('alt')); }); $('img').queue('chain', function(){ console.log('Third: ' + $(this).attr('alt')); }); $('img').queue('chain', function(){ console.log('Fourth: ' + $(this).attr('alt')); }); $('button').click(function(){ $('img').dequeue('chain'); }); ==> 결과 처음 클릭 First: Earth First: Moon 두번째 클릭 Second: Earth Second: Moon .... 한큐씩 꺼내온다. => $('img').queue('chain',function(){ console.log('First: ' + $(this).attr('alt')); $(this).dequeue('chain'); }); $('img').queue('chain',function(){ console.log('Second: ' + $(this).attr('alt')); $(this).dequeue('chain'); }); $('img').queue('chain',function(){ console.log('Third: ' + $(this).attr('alt')); $(this).dequeue('chain'); }); $('img').queue('chain',function(){ console.log('Fourth: ' + $(this).attr('alt')); $(this).dequeue('chain'); }); $('button').click(function(){ $('img').dequeue('chain'); }); ==> 결과 시동을 해주면 한꺼번에 꺼내 실행한다. 순서 차이가 있다. First: Earth Second: Earth Third: Earth Fourth: Earth First: Moon Second: Moon Third: Moon Fourth: Moon -- clearQueue( [ queueName ] ) : 큐에 저장되어있던 아직 실행되지 않은 모든 아이템를 제거 -- delay( duration, [ queueName ] ) : 큐의 실행을 듀레이션동안 딜레이 ex) => $('img').queue('chain',function(){ console.log('First: ' + $(this).attr('alt')); $(this).dequeue('chain'); }); $('img').delay(1000,'chain');// 딜레이 $('img').queue('chain',function(){ console.log('Second: ' + $(this).attr('alt')); $(this).dequeue('chain'); }); $('img').queue('chain',function(){ console.log('Third: ' + $(this).attr('alt')); $(this).dequeue('chain'); }); $('img').queue('chain',function(){ console.log('Fourth: ' + $(this).attr('alt')); $(this).dequeue('chain'); }); $('button').click(function(){ $('img').dequeue('chain'); }); ==> 결과 시동을 해주면 한꺼번에 꺼내 실행한다. 순서 차이가 있다. First: Earth First: Moon -> 여기서 일초간 딜레이 Second: Earth Third: Earth Fourth: Earth Second: Moon Third: Moon Fourth: Moon -- 큐에 특정 함수 집어넣기 ex1) 실행하자마자 보더값이 바뀐다. $( 'button' ).click(function() { $( 'img[alt=Moon]' ).animate({ left:'+=200' },1000); $( 'img[alt=Moon]' ).animate({ top:'+=200' },1000); $( 'img[alt=Moon]' ).css('border','4px solid navy'); $( 'img[alt=Moon]' ).animate({ left:'-=200' },1000); $( 'img[alt=Moon]' ).animate({ top:'-=200' },1000); }); ex2) 순서대로 보더값이 바뀐다. $( 'button' ).click(function() { $( 'img[alt=Moon]' ).animate({ left:'+=200' },1000); $( 'img[alt=Moon]' ).animate({ top:'+=200' },1000); $( 'img[alt=Moon]' ).queue(function() { $(this).css({border:'4px solid navy'}); $(this).dequeue(); }) $( 'img[alt=Moon]' ).animate({ left:'-=200' },1000); $( 'img[alt=Moon]' ).animate({ top:'-=200' },1000); }); 8. 제이쿼리 유틸함수 8.1 제이쿼리 플랙 사용하기 8.1.1 애니메이션 사용정지 시키기 - $.fx.off : true 값이 설정되면 전역에서 애니메이션이 정지된다. 8.1.2 $.support 8.1.3 $.browser 8.2 제이쿼리와 함께 다른 라이브러리 사용하기 ex) <script type="text/javascript" src="other_lib.js"></script> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $.noConflict(); jQuery(document).ready(function($) { // Code that uses jQuery's $ can follow here. }); // Code that uses other library's $ can follow here. </script> 8.3 자바스크립트 코어 오브젝트 다루기 8.3.1 jQuery.trim( str ) Returns: String 8.3.2 jQuery.each( collection, callback(indexInArray, valueOfElement) ) Returns: Object 8.3.3 jQuery.grep( array, function(elementOfArray, indexInArray), [ invert ] ) Returns: Array -function : 논리값 반환,true 반환하면 그 요소는 살아 남는다. -invert : 기본값 false, true로 설정하면 false 반환시 그 요소가 살아 남는다. ex) var arrData=[1,9,3,8,6,1,5,9,4,7,3,8,6,9,1]; $( 'div#one' ).text( arrData.join(',')); arrData=$.grep(arrData,function(ad,ai) { return (ad !=5 && ai >4 ); }) $( 'div#two' ).text( arrData.join(',') ); 8.3.4 jQuery.map( array, callback(elementOfArray, indexInArray) ) Returns: Array 8.3.5 jQuery.inArray( value, array ) Returns: Number 배열 검색후 매치되는 원소 인덱스 번호 리턴, 매치되는 원소가 없으면 -1 반환 8.3.6 jQuery.makeArray( obj ) Returns: Array 배열과 유사한객체(컬렉션)를 배열로 반환 8.3.7 jQuery.unique( array ) Returns: Array DOM 엘리먼트의 배열을 중복제거한후 정렬하여 반환. 문자나 숫자원소 배열에서는 동작하지 않는다. 8.3.8 jQuery.merge( first, second ) Returns: Array 첫번째 배열에 두번째 배열을 합친다. 원본 배열 변경 ex1) 원본배열 변경 var arrData1=['a','b','c']; var arrData2=['d','e','f']; $.merge(arrData1,arrData2); console.log(arrData1); => ["a", "b", "c", "d", "e", "f"] ex2) 원본배열 유지 var arrData1=['a','b','c']; var arrData2=['d','e','f']; var arrData3=$.merge( $.merge([],arrData1),arrData2 ); console.log(arrData1); console.log(arrData3); => ["a", "b", "c"] ["a", "b", "c", "d", "e", "f"] 8.4 객체의 확장 8.4.1 jQuery.extend( target, [ object1 ], [ objectN ] ) Returns: Object - jQuery.extend( target, [ object1 ], [ objectN ] ) - jQuery.extend( [ deep ], target, object1, [ objectN ] ) deep : If true, the merge becomes recursive (aka. deep copy). target : The object to extend. It will receive the new properties. object1 : An object containing additional properties to merge in. objectN : Additional objects containing properties to merge in. ex) var object1 = { apple: 0, banana: {weight: 52, price: 100}, cherry: 97 }; var object2 = { banana: {price: 200}, durian: 100 }; //$.extend(object1, object2); $.extend(true,object1, object2); console.log(object1); 8.5 직렬화 8.5.1 jQuery.param( obj ) Returns: String => query string - jQuery.param( obj ) - jQuery.param( obj, traditional ) ex) var myObject = { a: { one: 1, two: 2, three: 3 }, b: [1,2,3] }; var queryString1=$.param(myObject); console.log( queryString1 ); // a%5Bone%5D=1&a%5Btwo%5D=2&a%5Bthree%5D=3&b%5B%5D=1&b%5B%5D=2&b%5B%5D=3 console.log( decodeURIComponent( queryString1 ) ); // a[one]=1&a[two]=2&a[three]=3&b[]=1&b[]=2&b[]=3 var myObject1={ 'a thing':'it&s=value', 'another thing':'another value', 'weird characters':'!@#$%^&*()_+=' } var queryString2=$.param(myObject1); console.log( queryString2 ); //a+thing=it%26s%3Dvalue&another+thing=another+value&weird+characters=!%40%23%24%25%5E%26*()_%2B%3D console.log( decodeURIComponent( queryString2 ) ); //a+thing=it&s=value&another+thing=another+value&weird+characters=!@#$%^&*()_+= 8.6 객체 테스트 - $.isArray(o) - $.isEmptyObject(o) - $.isFunction(o) - $.isPlainObject(o) - $.isXMLDoc(node) 8.7 Doing Nothing - $.noop() 8.8 jQuery.contains( container, contained ) Returns: Boolean - container : The DOM element that may contain the other element. - contained : The DOM node that may be contained by the other element. 8.9 jQuery.data() - jQuery.data( element, key, value ) Returns: jQuery - jQuery.data( element, key ) Returns: Object 8.10 $.removeData(element, key) 8.11 jQuery.proxy() => 실행시 컨텍스트를 바꾸어 준다. - jQuery.proxy( function, context ) -- function : The function whose context will be changed. -- context : The object to which the context (this) of the function should be set. - jQuery.proxy( context, name ) -- context : The object to which the context of the function should be set. -- name : The name of the function whose context will be changed (should be a property of the context object). ex) <p><button id="test" name="button">Test</button></p> <p id="log"></p> => var obj = { name: "John", test: function() { $("#log").append( this.name ); $("#test").unbind("click", obj.test); } }; //$("#test").click( obj.test ); // button 출력 $("#test").click( $.proxy(obj.test,obj) ); // john 출력 => $("#test").click( jQuery.proxy( obj, "test" ) ); // john 출력 8.12 jQuery.parseJSON( json ) Returns: Object - json : The JSON string to parse. 8.13 jQuery.globalEval( code ) ex) function test1(){ jQuery.globalEval("var newVar1 = true;") } function test2(){ eval("var newVar2 = true;") console.log(newVar2) // 동작 지역변수를 유효범위 안에서 사용 } test1(); test2(); console.log( newVar1 ); //전역변수 이기 때문에 동작 console.log( newVar2 ); //에러! 지역변수 이기 때문에 8.14 jQuery.getScript( url, [ success(data, textStatus) ] ) Returns: XMLHttpRequest : HttpRequest를 이용 자바스크립트파일을 로드한후 실행 - jQuery.getScript( url, [ success(data, textStatus) ] ) ex) $.getScript("http://dev.jquery.com/view/trunk/plugins/color/jquery.color.js", function(){ $("#go").click(function(){ $(".block").animate( { backgroundColor: 'pink' }, 1000) .animate( { backgroundColor: 'blue' }, 1000); }); }); 9. 제이쿼리를 확장하기 9.1 $ 충돌문제 (function($){ // // Plugin definition goes here // })(jQuery); 9.2 동적인 매개값 해결 function complex(p1,options) { var settings = $.extend({ option1: defaultValue1, option2: defaultValue2, option3: defaultValue3, option4: defaultValue4, option5: defaultValue5, option6: defaultValue6 },options || {}); // remainder of function ... } // complex('aa', {aa:'aa',bb:'bb'}); 9.3 일반함수 만들기 (function($){ $.say = function(what) { alert('I say '+what); }; })(jQuery); 9.4 새로운 래퍼 메써드 추가하기 9.4.1 일반적인 패턴 (function($) { $.fn.makeItBlue=function() { return this.css('color','red'); } })(jQuery); jQuery(function() { $( '#test' ).makeItBlue(); }); ** $.fn 은 단순히 제이쿼리 객체를 생성해주는 클래스 prototype 의 앨리어스 이다. ** 위 추가된 메써드안에서의 this는 래퍼객체이다. 만약 함수안에서 each() 와 같은 메써드를 사용한다면 each() 안의 this는 코어 객체가 된다. (function($){ $.fn.someNewMethod = function() { return this.each(function(){ // // Function body goes here -- this refers to individual // DOM elements // }); }; })(jQuery); (function($){ $.fn.makeItBlueOrRed = function() { return this.each(function(){ $(this).css('color',$(this).is('[id]') ? 'blue' : 'red'); }); }; })(jQuery); == (function($){ $.fn.makeItBlueOrRed = function() { return this.css('color',function() { return $(this).is('[id]') ? 'blue' : 'red'; }); }; })(jQuery); 9.4.2 래퍼 메써드에 다중 기능 추가 (function($){ $.fn.setReadOnly = function(readonly) { return this.filter('input:text') .attr('readOnly',readonly) .css('opacity', readonly ? 0.5 : 1.0) .end(); }; })(jQuery); 10. AJAX 10.11 .load( url, [ data ], [ complete(responseText, textStatus, jqxhr) ] ) Returns: jQuery url : 요청 url data : 서버측으로 전송할 맵 또는 문자열 complete(responseText, textStatus, XMLHttpRequest) : 요청이 완료된후 호출되는 함수 ex) $( '#rstBox' ).load('./dataHtml.html #dataUrl'); $( '#rstBox' ).load('./notHere.php',function(response,status,xhr) { console.log ( response ); console.log ( status ); console.log ( xhr ); }); textStatus => success,notmodified,error,timeout,abort,parsererror 10.12 .serialize() Returns: String : 랩 셋 폼 엘리먼트로 부터 인코딩된 쿼리 스트링을 생성한다. 10.13 .serializeArray() Returns: Array ex) $('form').submit(function() { console.log($(this).serializeArray()); return false; }); => [ { name: a value: 1 }, { name: b value: 2 }, { name: c value: 3 }, { name: d value: 4 }, { name: e value: 5 } ] 10.14 jQuery.get( url, [ data ], [ success(data, textStatus, jqXHR) ], [ dataType ] ) Returns: jqXHR => jQuery.ajax 함수의 단축 함수 $.ajax({ type:'GET', url: url, data: data, success: success, dataType: dataType }); - url : A string containing the URL to which the request is sent. - data : A map or string that is sent to the server with the request. - success(data, textStatus, jqXHR) : A callback function that is executed if the request succeeds. - dataType : The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html). xml,html,script,json,jsonp,text Example: Gets the test.php page contents which has been returned in json format (<?php echo json_encode(array("name"=>"John","time"=>"2pm")); ?>). $.get("test.php", { "func": "getNameAndTime" }, function(data){ alert(data.name); // John console.log(data.time); // 2pm }, "json"); 10.15 jQuery.post( url, [ data ], [ success(data, textStatus, jqXHR) ], [ dataType ] ) Returns: jqXHR => jQuery.ajax 함수의 단축 함수 $.ajax({ type: 'POST', url: url, data: data, success: success, dataType: dataType }); 10.16 jQuery.getJSON( url, [ data ], [ success(data, textStatus, jqXHR) ] ) Returns: jqXHR => jQuery.ajax 함수의 단축 함수 $.ajax({ url: url, data: data, success: success, dataType: 'json' }); ### jQuery 1.5 부터 모든 제이쿼리 Ajax 메써드는 XMLHTTPRequest 객체의 수퍼 셋을 반환 한다. - 프로퍼티 및 메써드 readyState 4 responseText "<!DOCTYPE html PUBLIC "...</ul>\r\n</body>\r\n</html>" status 200 statusText "parsererror" abort function() complete function() done unction() error function() fail function() getAllResponseHeaders function() getResponseHeader function() isRejected function() isResolved function() overrideMimeType function() promise function() setRequestHeader function() statusCode function() succe function() then function() ex) // Assign handlers immediately after making the request, // and remember the jqxhr object for this request var jqxhr = $.getJSON("example.json", function() { alert("success"); }) .success(function() { alert("second success"); }) .error(function() { alert("error"); }) .complete(function() { alert("complete"); }); // perform other work here ... // Set another completion function for the request above jqxhr.complete(function(){ alert("second complete"); }); #### JSONP 동일 출처 정책은 동적 스크립트 요소의 문서 내 삽입은 허용하기 때문에 다른 도메인의 JavaScript를 동적으로 삽입하여 JSON 데이터를 전달할 수 있다. 이처럼 함수 호출에 랩핑된 JSON 데이터를 JSONP(JSON with Padding)라고 한다. 이 작업을 수행하려면 코드를 삽입하기 전에 콜백 함수가 미리 정의되어 있어야 한다. ex) jQuery(function() { jQuery.getJSON( "http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",function(data){ for(var prop in data.items) { $( '#catPhotoBox').append('<p><img src="'+data.items[prop].media['m']+'"></p>'); } }); }); ***동일 출처 정책 제한 이해 동일 출처 정책은 한 도메인에서 로드된 스크립트가 다른 도메인의 문서 특성을 가져오거나 조작하지 못하도록 한다. 즉, 요청된 URL의 도메인이 현재 웹 페이지의 도메인과 같아야 한다. 이는 기본적으로 브라우저가 다른 출처의 컨텐츠를 조작하는 것을 방지하기 위해 해당 컨텐츠를 분리한다는 것을 의미한다. 10.17 jQuery.ajax( url, [ settings ] ) Returns: jqXHR => Ajax 요청의 통합 메써드 http://api.jquery.com/jQuery.ajax/ - jQuery.ajax( url, [ settings ] ) - jQuery.ajax( settings ) -- settings async : 비동기 여부 불리언값 ,기본값 true beforeSend(jqXHR, settings) : ajax 전송전 header나 referer 변조 ex) $.ajax({ type : "POST", url : urls, data : params, beforeSend: function(xhr) { xhr.setRequestHeader("referer", http://drst3in.webdoor.co.kr); }, error : function(e){ alert(e); }, success : function(data){ $("body").html(data); } }); cache : 기본값 true, dataType이 script 과 jsonp라면 false, false로 셋팅하면 브라우저에 의해 요청페이지가 캐시되지 않는다. complete(jqXHR,textStatus) : 요청이 완료되었을때 호출될 함수. jQuery 1.5 버전부터는 함수배열을 받을 수 있고 각 함수는 차례로 호출된다. http://docs.jquery.com/Ajax_Events textStatus => success,notmodified,error,timeout,abort,parsererror contentType : 기본값은 "application/x-www-form-urlencoded" 폼 전송시에도 이값이다. context : 컨텍스트 지정( this ) ex) $.ajax({ url: "test.html", context: document.body, success: function(){ $(this).addClass("done"); } }); converters ( add 1.5 ) : 데이타 타입 변환기 기본값은 {"* text": window.String, "text html": true, "text json": jQuery.parseJSON, "text xml": jQuery.parseXML} crossDomain(added 1.5) : 기본값은 같은 도에인 요청일경우 false,다른 도메인 일 경우 true; data : 서버로 전송할 데이터, -> Object or String dataFilter(data,type) : dataType : 서버로부터 되돌려 받기을 원하는 데이타의 타입, 기본값은 자동으로 설정된다.(xml, json, script, or html) xml,html,script,json,jsonp,text error(jqXHR, textStatus, errorThrown) : textStatus -> error,timeout,notmodified,parsererror jsonp : jsonp 요청에서 callback 함수 명을 덮어 쓴다. 이값은 요청 url의 쿼리스트링 부분인 'callback=?' 이부분의 callback 대신 사용할 문자열(함수명)이다. scriptCharset : GET 방식을 이용한 jsonp 또는 script 데이터 타입일경우에만 사용할 수 있다. 로컬과 리모트 사이의 캐릭터 셋이 다를경우 사용 statusCode : 상태코드 맵 기본값은 {} ex) $.ajax({ statusCode: { 404: function() { alert('page not found'); } } }); success(data, textStatus, jqXHR) : 요청 성공시 호출될 함수 timeout : 밀리초 단위 , 요청 단위로 제한 시간을 준다. 글로벌 셋팅은 $.ajaxSetup()를 이용 type : 기본값은 GET url : 기본값은 현재 페이지 10.18 jQuery.ajaxSetup( options ) : 모든 ajax 요청의 기본 설정 셋 ex) $.ajaxSetup({ type: 'POST', timeout: 5000, dataType: 'html' }); 10.19 AJAX Event ajaxStart (Global Event) 이 이벤트는 ajax 요청이 시작되고 다른 어떤 ajax 요청도 현재 동작하지 않을때 전파된다. beforeSend (Local Event) : 이 이벤트는 ajax요청이 시작되기전에 점화되는데 ajax 오브젝트를 수정하는데 사용된다. ajaxSend (Global Event) : 이 글로벌 이젠트로 ajax요청이 시작되기전 점화된다. success (Local Event) : 이 이벤트는 요청이 성공했을때에만 호출된다. ajaxSuccess (Global Event) : 이 이벤트 또한 요청이 성공했을때에만 호출된다. error (Local Event) : 요청에 에러가 발생했을때 호출된다. ajaxError (Global Event) : 요청에 에러가 발생했을때 호출된다. complete (Local Event) : 어떠한 경우든 요청이 완료되었을때 호출 ajaxComplete (Global Event) : 어떠한 경우든 요청이 완료되었을때 호출 ajaxStop (Global Event) : 이 글로벌 이벤트는 더이상 ajax 요청이 처리되고 있지 않을때 점화 된다. -- 글로벌 이벤트 핸들러 ajaxComplete( handler(event, XMLHttpRequest, ajaxOptions) ) ....ajaxError,ajaxSend,ajaxStart,ajaxStop,ajaxSuccess 글로벌 이벤트는 특정 요청에서 아래와 같이 global 옵션이 셋팅되면 사용할 수 없다. ex) $.ajax({ url: "test.html", global: false, // ... }); ex) <div class="trigger">Trigger</div> <div class="result"></div> <div class="log"></div> $('.log').ajaxComplete(function() { $(this).text('Triggered ajaxComplete handler.'); }); or $('.log').ajaxComplete(function(e, xhr, settings) { if (settings.url == 'ajax/test.html') { $(this).text('Triggered ajaxComplete handler. The result is ' + xhr.responseText); } }); $('.trigger').click(function() { $('.result').load('ajax/test.html'); }); 11. jQuery UI - themes and effects - Effects - Interactions - Widgets 11.1 다운로드및 커스텀 셋팅 http://jqueryui.com/themeroller/ 11.2 effect( effect, [options], [speed], [callback] ) http://jqueryui.com/demos/effect/ - effect : 'blind', 'bounce', 'clip', 'drop', 'explode', 'fold', 'highlight', 'puff', 'pulsate', 'scale', 'shake', 'size', 'slide', 'transfer' - options : - speed : ("slow", "normal", or "fast") or the number of milliseconds - callback : 11.3 animate() 메써드의 확장 backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color outlineColor ex) $(function() { $( "#button" ).toggle( function() { $( "#effect" ).animate({ backgroundColor: "#aa0000", color: "#fff", width: 500 }, 1000 ); }, function() { $( "#effect" ).animate({ backgroundColor: "#fff", color: "#000", width: 240 }, 1000 ); } ); }); 11.4 show(),hide(),toggle()의 확장 - show( effect, [options], [speed], [callback] ) http://jqueryui.com/demos/show/ - hide( effect, [options], [speed], [callback] ) - toggle( effect, [options], [speed], [callback] ) 11.5 클래스 메써드의 확장 - addClass(class,speed,easing,callback) - removeClass(class,speed,easing,callback) - toggleClass(class,force,speed,easing,callback) - switchClass(removed,added,speed,easing,callback) ex) $( '#button' ).click(function() { $('#effect').switchClass('effect','effect01',1000,'easeInBounce'); return false; }); 11.6 Easing linear easeInOutQuart easeOutCirc swing easeInQuint easeInOutCirc jswing easeOutQuint easeInElastic easeInQuad easeInOutQuint easeOutElastic easeOutQuad easeInSine easeInOutElastic easeInOutQuad easeOutSine easeInBack easeInCubic easeInOutSine easeOutBack easeOutCubic easeInExpo easeInOutBack easeInOutCubic easeOutExpo easeInBounce easeInQuart easeInOutExpo easeOutBounce easeOutQuart easeInCirc easeInOutBounce 12. jQuery UI - mouse interactions - 코어 마우스 상호작용 - 드래그 앤 드롭 의 구현 - 정렬기능 - 크기 변경 - 선택가능하게 만들기 12.1 드래그 - draggable(options) : 처음 설정시 사용 -- addClasses : 기본값 true,false로 설정하게되면 ui-draggable 클래스가 해당엘리먼트에 셋팅 되지 않는다. ex) --- 초기 설정시 --- $( ".selector" ).draggable({ addClasses: false }); --- 초기 설정후 --- //getter var addClasses = $( ".selector" ).draggable( "option", "addClasses" ); //setter $( ".selector" ).draggable( "option", "addClasses", false ); -- disabled : 처음부터 일시적인 드래그 사용금지 ex) --- 초기 설정시 --- $( ".selector" ).draggable({ disabled: true }); --- 초기 설정후 --- /getter var disabled = $( ".selector" ).draggable( "option", "disabled" ); //setter $( ".selector" ).draggable( "option", "disabled", true ); -- appendTo : helper의 컨테이너가 된다. 기본값 parent $( ".selector" ).draggable({ appendTo: 'body' }); -- helper : 옵션값은 'clone' 또는 'original' 또는 함수이어야 하고 이 함수는 DOM엘리먼트를 반환하여여한다. clone 옵션값이 주어지면 복제본이 만들어져 드래그 된다. -- axis : 드래그 방향지정 'x' 또는 'y' 기본값 false $( ".selector" ).draggable({ axis: 'x' }); -- cancel : 특정 엘리먼트 드래그 금지 기본값은 'input , option' -- connectToSortable : sortable() 메써드가 적용된 엘리먼트에 드래그 허용, 이 옵션이 사용되면 ( helper 옵션값이 'clone'이 되어야 정확하게 작동한다.) 드래그 되는 엘리먼트가 sortable 리스트에 드롭되어 그 리스트의 일 부분이 된다. ex) <script type="text/javascript"> jQuery(function() { $('#targetList').sortable(); $( '#dragMe li' ).draggable({connectToSortable:'#targetList',helper:'clone'}); }); </script> </head> <body> <h1>jQueryUI draggable()</h1> <ul id="targetList"> <li>orange</li> <li>nuts</li> <li>melon</li> </ul> <ul id="dragMe"> <li>apple</li> <li>banana</li> <li>grape</li> </ul> -- containment : 드래그 범위 지정, 가능한값 'parent','document','window',[x1,y1,x2,y2] -- cursor : 드래그가 진행되는 동안 커서 모양 -- cursorAt : 드래그가 진행되는 동안의 커서의 좌표(주로 helper 값이 clone일 경우 사용), {top,left,right,bottom} $( '#childBox' ).draggable({cursorAt: { left:0,top:0 },helper:'clone'}); -- delay : 드래그가 시작되었을때 딜레이 밀리초 -- distance : 어느정도 마우스가 움직여야 드래그가 되나. 기본값 1 -- grid : 드래그 할때 한번에 움직이는 거리 [x,y] -- handle : Element, Selector 해당되는 엘리먼트를 클릭해야만 드래그 해야만 드래그 $( '#childBox' ).draggable({ handle: 'h2' }); => 박스 하위 h2를 클릭하여 드래그 하여야한다. -- opacity : 드래그 하는동안의 불투명도 -- revert : true로 설정되면 드래그가 멈추었을때 원래 자리로 돌아온다. 'valid' 또는 'invalid' 값이 설정될 수 있는데 'invalid' 값이 설정되면 드롭할 수 없는 곳에 드롭되었을때에만 되돌아온다. -- revertDuration : 되돌아 오는데 걸리는 밀리초, revert가 활성화 되어야만 의미가 있다. 기본값 500 -- scope -- scroll : 드래그할때 스크롤바 생성 여부 ,기본값 true -- snap : true or selector $( '#childBox' ).draggable({ snap: '#parentBox'}); -- snapMode : inner or outer or both $( '#childBox' ).draggable({ snap: '#parentBox',snapMode:'outer'}); -- snapTolerance : 기본 20, 스냅거리 $( '#childBox' ).draggable({ snap: '#parentBox',snapTolerance:40}); -- stack : 매칭되는 선택자보다 항상 위에 배치(z-index 값을 매칭선택자 보다 크게) $( '#childBox' ).draggable({stack:'#button1'}); -- zIndex : 드래그 되는동안의 z-index값 ( 보통 helper 사용할때 유용) ---이벤트 관련--- -- create : type -> dragcreate ex) $( ".selector" ).draggable({ create: function(event, ui) { ... } }); == $( ".selector" ).bind( "dragcreate", function(event, ui) { ... }); -- start : type -> dragstart -- drag : type -> drag -- stop : type -> dragstop - draggable('disable') : 일시적으로 드래그를 사용 못하게 한다. - draggable('enable') : 일시적으로 드래그금지를 푼다. - draggable('destroy') : 드래그를 제거한다. - draggable('option',optionName,value) : 설정된 옵션값을 가져오거나 변경한다. - 드래그 이벤트 - 이 이벤트의 핸들러는 드래그되는 엘리먼트의 조상 엘리먼트에서도 사용할 수 있다. -- dragstart -- drag -- dragstop ex) $( '#childBox' ).draggable(); $('body').bind('dragstart',function(evt,info) { console.log(evt); console.log(info); }) -- 이벤트 핸들러의 파라미터 - event : 제이쿼리 이벤트 객체 - info : helper,position,offset,originalPosition 프로퍼티를 가지고 있는 객체 - 모든 드래깅 요소 드래깅 일시적으로 정지 시키기 다시 드래깅 가능하게 하기 -- $('.ui-draggable').draggable('disable'); => 모든 드래깅 요소는 ui-draggable 클래스를 가지므로 -- $('.ui-draggable').draggable('enable'); => 다시 드래깅 가능 12.2 드롭 - droppable(options) - 처음 설정시 사용 , ui-droppable 클래스가 해당 엘리먼트에 추가된다. -- accept : (selector | function) , 드래그를 허용할 엘리먼트 래퍼셋 또는 필터링함수, 필터링함수는 래퍼셋 각각의 엘리먼트를 파라미터로 받아 들인다. -- activeClass : (String) 드래그 되는동안만 드롭엘리먼트에 클래스 추가 -- addClasses : (Boolean) false로 설정되면 ui-droppable 클래스가 설정되지 않는다. 기본값 true -- greedy : (Boolean) true로 설정되면 이벤트 전파 중지 http://jquery-ui.googlecode.com/svn/tags/1.8.10/demos/droppable/propagation.html -- hoverClass : (String) hover시 설정되는 클래스 -- scope : (String) -- tolerance : 어느정도까지 드래그 돼야 드롭 이벤트가 발생하는지. fit(전체),inersect(반),pointer(마우스 포인터),touch(오버랩되는 부분이 있기만 하면) 기본값은 intersect ---- 이벤트 관련 -- create : type dropcreate ex) $( ".selector" ).droppable({ create: function(event, ui) { ... } }); == $( ".selector" ).bind( "dropcreate", function(event, ui) { ... }); -- activate : type dropactivate , 드래그가 활성화 되면 -- deactivate : type dropdeactivate , 드래그가 비활성화 되면 -- over : type dropover -- out : type dropout -- drop : type drop *** 이벤트 핸들러함수의 인자 - event : 제이쿼리 이벤트 객체 - ui : 드래그앤 드롭에 관련된 정보를 가지고 있는 객체 -- helper -- draggagle -- position : offset parent 기준 좌표 (left,top) -- offset : document 기준 기준 좌표 (left,top) - droppable('disable') - 이하 설정 값을 얻어 오거나 변경할때 사용 - droppable('enable') - droppable('destroy') - droppable('option',optionName,value) 12.3 Sorting
반응형
: