1 개요[ | ]
- How to manipulate with specific elements in jQuery Plugin
- jQuery 플러그인 만들기 2 - 개별요소 접근
- 개별 요소에 접근할 필요가 있다면 .each() 활용
- 흔히
return this.each(function() {})
로 표기됨 - 특수 문법이 아니라... 다음 2가지가 합쳐진 것
JavaScript
Copy
this.each(function() {
// 개별요소에 접근하여 할 일을 하고...
});
return this; // 자신을 반환...
2 예시 1[ | ]
redify()
의 경우는 전체에 적용하면 되므로 개별요소에 접근할 필요가 없음showCount()
는 각 요소의 값을 읽고 조작해야 하므로 개별요소에 접근할 필요가 있음
- 기능: 개별요소의 수량정보(data-count)를 읽고 각 text에 표시해줌
JavaScript
Copy
<script src="//code.jquery.com/jquery.min.js"></script>
<script>
// 플러그인
(function ( $ ) {
$.fn.redify = function() {
this.css( "color", "red" );
return this;
};
}( jQuery ));
(function ( $ ) {
$.fn.showCount = function() {
return this.each(function() {
$(this).append( ' (' + $(this).data('count')+'개)' );
});
};
}( jQuery ));
// 사용 예시
$(function() {
$('#fruits>li').showCount().redify();
});
</script>
<ul id='fruits'>
<li data-count='3'>사과</li>
<li data-count='5'>배</li>
</ul>
3 예시 2[ | ]
JavaScript
Copy
<script src="//code.jquery.com/jquery.min.js"></script>
<script>
// 플러그인
(function ( $ ) {
$.fn.showHref = function() {
return this.each(function() {
$(this).append( ' (' + $(this).attr('href')+')' );
});
};
}( jQuery ));
// 사용 예시
$(function() {
$('a').showHref();
});
</script>
<p><a href='http://naver.com'>네이버</a></p>
<p><a href='http://daum.net'>다음</a></p>
<p><a href='http://google.com'>구글</a></p>
4 같이 보기[ | ]
5 참고[ | ]
편집자 Jmnote Jmnote bot
로그인하시면 댓글을 쓸 수 있습니다.