خرید بک لینک

Vote count: 0

I'm trying to add an event listener to all li elements in a ul. I currently have the code working for the first list item as a proof but I'm not sure how to expand this to the entire list. I've tried several things like delegate(), on() and an each() but I keep coming up empty. Any help or suggestions would be greatly appreciated

(function() {
    var $body = document.body
    , $menu_trigger = $body.getElementsByClassName('menu-trigger')[0]
  , $menu_list_item = $body.getElementsByClassName('menu-list-item')[0];
// , $menu_list_items = $body.getElementsByClassName('menu-list-items');

    if ( typeof $menu_list_item !== 'undefined' ) {
        $menu_list_item.addEventListener('click', function() {
            $body.className = ( $body.className == 'menu-active' )? '' : 'menu-active';
        });
    }

    if ( typeof $menu_trigger !== 'undefined' ) {
        $menu_trigger.addEventListener('click', function() {
            $body.className = ( $body.className == 'menu-active' )? '' : 'menu-active';
        });
    }

}).call(this);

asked 9 mins ago

2 Answers

Vote count: 0

If you're using jQuery then you can use a selector to add a click event to multiple items.

Something like

$('.eventClass').on('click', function() {
  doSomething();
});

That'll be applied to any elements with the class "eventClass." You could use other CSS selectors if those would be better.

If you want pure javascript, use document.getElementsByClassName().

answered 2 mins ago

Vote count: 0

//wait dom to load
$(document).ready(function(){
   $('ul > li').click(function(){
     alert($(this).html());
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <ul>
    
    <li> A </li>   
        <li> B </li>   
        <li> C </li>   
      
  </ul>
  
  <div>
    <!-- example of nested -->
    <ul>
       <li> G </li>   
        <li> D </li>   
        <li> F </li>   
      
    </ul>
   
   </div>
 </body>
    

Click on any :) With jquery you just must specify css selctor of targeted elements :)

answered 1 min ago

برچسب: نویسنده: استخدام کار تاريخ: يکشنبه 10 مرداد 1395 ساعت: 10:42

صفحه بندی