首页 > 技术文章 > jQuery实现可折叠面板(事件委托)

darthbadwolf 2017-08-09 14:13 原文

jQuery的事件

jQuery中使用.on()方法来处理事件. 具体可以看之前写的jQuery基本知识

 

可折叠面板

页面上有3个li, 在默认状态下是折叠起来的(图1)

在点击之后, 面板展开, 再次点击的时候, 面板收起

 

HTML部分代码

 1  <body>
 2 
 3     <header><h1>Monsieur Pigeon</h1></header>
 4 
 5     <section class="page">
 6       <ul class="accordion" id="accordion">
 7         <li>
 8           <button class="accordion-control">Classics</button>
 9           <div class="accordion-panel">
10             <p>If you like your flavors traditional, Monsieur Pigeon's classic marshmallows won't disappoint. With luxuriously <strong>Velvety Vanilla</strong>, <strong>Charming Chocolate</strong>, and <strong>Sumptuous Strawberry</strong>, the favorites you love are treated with the respect and dignity they deserve!</p>
11           </div>
12         </li>
13         <li>
14           <button class="accordion-control">The Flower Series</button>
15           <div class="accordion-panel">
16             <p>Take your tastebuds for a gentle stroll through an English garden filled with Monsieur Pigeon's beautifully fragrant Flower Series marshmallows. With three sweetly floral options: <strong>Elderberry</strong>, <strong>Rose Petal</strong>, and <strong>Chrysanthemum</strong> - all edible and all naturally flavored - they will have you dreaming of butterflies and birdsong in no time.</p>
17           </div>
18         </li>
19         <li>
20           <button class="accordion-control">Salt o' The Sea</button>
21           <div class="accordion-panel">
22             <p>Ahoy! If you long for a taste of organic sea salt mixed in with your sweet Monsieur Pigeon marshmallows, look no further than our Salt o' the Sea range. Featuring two delicious flavors: <strong>Salted Caramel</strong> and <strong>Cashew Butter</strong>, this sweetly salty duo will expand your taste horizons.</p>
23           </div>
24         </li>
25       </ul>
26     </section>
27 
28 
29   </body>

 

 

jQuery实现

在这里使用了事件委托机制.

在.accordion-control的公共父元素accordion上绑定了click事件, 利用DOM事件冒泡机制来统一委托处理.

当出发了某个元素的click事件, JS会一次通知该元素及其父元素...知道最顶部的document对象位置.
如果这些元素上绑定了click事件处理函数, 就会依次执行.
在本例中, 事件委托机制就是, 不为每个button元素直接绑定click事件处理函数, 而是委托给ul元素, '告诉'他: 如果收到了click
事件触发匿名函数, 并且这个click事件时有这些button元素其中之一触发的, 就执行祖辈元素上委托绑定的事件处理函数.

1 $('.accordion').on('click', '.accordion-control', function(e){ // When clicked
2   e.preventDefault();                    // Prevent default action of button
3   //console.log($(this).attr('class'));
4   $(this)       // Get the element the user clicked on  这里的this指向触发click事件的accordion-control类(可以从上一句console得知)
5     .next('.accordion-panel')            // Select following panel
6     .not(':animated')                    // If it is not currently animating
7     .slideToggle();                      // Use slide toggle to show or hide it
8 });

 

推荐阅读