colin
colin

Reputation: 43

How to implement a jQUery switch statement to find a class?

I have a list, and I want to run a switch statement for whether or not the clicked element has a certain class - then hide all the others.

Here's what I have, but the switch statement doesn't pick up the variable set with the click.

<ul>
  <li class="all"><a>Show all</a></li>
  <li class="design"><a>Design</a></li>
  <li class="dev"><a>Development</a></li>
  <li class="ux"><a>UX</a></li>
  <li class="print">Print</a></li>
</ul>

and:

$(function() {
$('a').click(function() {
    var wrkType = $(this).parent().attr('class')

    //alert(day) // alerts !
    });
});

 switch (wrkType)
{
case 'dev':
  alert('yahmon!')
  if (!$('li').hasClass('dev')) { $('li').fadeOut(300); }
  break;
case 'all':
  //All things on
  break;
} 

How can I achieve this?

Upvotes: 0

Views: 2622

Answers (2)

26ph19
26ph19

Reputation: 393

This should work

$(function() {
   $('a').on('click', function() {
    var wrkType = $(this).parent().attr('class')
     WorkType(wrkType);
    //alert(day) // alerts !
    });
});

 function WorkType (wrkType) {
 switch (wrkType)
 {
    case 'dev':
      alert('yahmon!')
      if (!$('li').hasClass('dev')) { $('li').fadeOut(300); }
    break;
    case 'all':
      //All things on
    break;
}
}

I would suggest to use on instead of click.

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 122008

If you are accessing the variable in other function,Make your workType variable global.Now it is local to the click callback function.

If you want to run in the same click event callback,Move your switch code to inside the callback function.

like this

$('a').click(function() {
   var wrkType = $(this).parent().attr('class')
   switch(wrkType ){
      case 'dev':
   --  

 --  
   }
});

Upvotes: 1

Related Questions