.delegate()
오늘 일하다가 눈에 띈 몇가지 jQuery API를 공부해 보겠습니다.
다른 사람이 만든 소스를 보다 보니까 .delegate() 메소드를 사용한게 있었는데요.
jQuery API에는 이 .delegate() 메소드는 1.4.3 버전에서 사용한 것이고 1.7 버전에서는 .on() 메소드를 사용하고 있다고 하네요.
그 신택스는 아래와 같네요.
$(elements).delegate(selector, events, data, handler); // jQuery 1.4.3+ $(elements).on(events, selector, data, handler); // jQuery 1.7+
약간 바뀌었죠.$("table").delegate("td", "click", function() { $(this).toggleClass("chosen"); });
위 소스코드는 1.7 버전에서 아래와 같이 사용할 수 있다고 합니다.
$("table").on("click", "td", function() { $(this).toggleClass("chosen"); });
그럼 곧바로 예제를 보죠.
<!DOCTYPE html>
<html>
<head>
<style>
p { background:yellow; font-weight:bold; cursor:pointer;
padding:5px; }
p.over { background: #ccc; }
span { color:red; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p>Click me!</p>
<span></span>
<script>
$("body").delegate("p", "click", function(){
$(this).after("<p>Another paragraph!</p>");
});
</script>
</body>
</html>
스크립트 부분을 보면 <body> 내에서 p 태그안에 있는 콘텐츠를 클릭하면 그 p 태그 다음에 <p> Another paragraph!</p> 를 추가하는 겁니다.
두번째 샘플을 보죠
<!DOCTYPE html>
<html>
<head>
<style>
p { color:red; }
span { color:blue; }
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p>Has an attached custom event.</p>
<button>Trigger custom event</button>
<span style="display:none;"></span>
<script>
$("body").delegate("p", "myCustomEvent", function(e, myName, myValue){
$(this).text("Hi there!");
$("span").stop().css("opacity", 1)
.text("myName = " + myName)
.fadeIn(30).fadeOut(1000);
});
$("button").click(function () {
$("p").trigger("myCustomEvent");
});
</script>
</body>
</html>
스크립트를 해석해 보자면.
먼저 밑에 button 부분을 봐야 겠네요.
버튼이 클릭되면 myCustomEvent 가 trigger 되네요.
그 다음에 delegate 부분을 봐야 되는데요.
이 myCustomEvent가 trigger 되면 p 태그 부분을 Hi there! 로 고치고 span 부분에 myName = myName 을 표시하는데 잠깐 나타났다가 서서히 사라지는 효과가 나타납니다.
'jQuery Mobile > jQuery API' 카테고리의 다른 글
우아하게 화면 scroll 하기 (0) | 2012.12.20 |
---|---|
.clone() 메소드 알아보기 (0) | 2012.08.23 |
.find() 메소드 알아보기 (0) | 2012.08.23 |
jQuery API 몇개 훑어보기 .html(), .text(), .bind() (0) | 2012.08.10 |
jQuery API .live() 공부하기 (2) | 2012.08.09 |