Reputation: 53
New to jQuery and I have a question about event delegation. Here below is a series of codes from javascript book
HTML:
<ul class="accordion">
<li>
<button class="accordion-control">Classics</button>
<div class="accordion-panel">
<p>If you ...</p>
</div>
</li>
<li>
<button class="accordion-control">The Flower Series</button>
<div class="accordion-panel">
<p>Take your ...</p>
</div>
</li>
<li>
<button class="accordion-control">Salt o' The Sea</button>
<div class="accordion-panel">
<p>Ahoy! ....</p>
</div>
</li>
</ul>
jQuery:
$('.accordion').on('click', '.accordion-control', function(e){
e.preventDefault();
$(this).next('.accordion-panel')
.not(':animated')
.slideToggle();
});
I was wondering since we have already selected '.accordion',then why should we also need to select '.accordion-control'? And I used to believe the formula should be $(selector).on(event,function)
,so there is another selector after the event?
Upvotes: 2
Views: 59
Reputation: 11367
The first accordion
refer to the ancestor. The binding will be on the click
event, for one of it's descendant called accordion-control
.
The ancestor is used when the descendant is not exist yet (for example if your accordion-control
are created using script and not exist from page loading (in HTML) - and then you cannot bind event to non-existing elements. If it's not your case (means your accordion-conrtol
's are exist from the beginning), you can also use the $(selector).click(function)
for that:
$('accordion-control').click(function (event) { //your code });
For more information you can look at: http://api.jquery.com/on/
Upvotes: 1