JQuery matching one class to a predefined list, where an element has multiple classes

I am trying to figure out if there is a way to do .hasClass() several times to see if the active element I'm working with is one of four classes currently. I am also trying to find the most optimized way to do this, while the element (s) that act as a trigger (or active element) have several classes in it, mainly for styling purposes.

HTML example:

 <div class="form_row"> <div class="primary_row">1</div> </div> <div class="form_row"> <div class="primary_row subexists">1</div> <div class="primary_row_sub">1a</div> </div> <div class="form_row"> <div class="primary_row subexists">1</div> <div class="primary_row_sub subexists">1a</div> <div class="secondary_row">2</div> </div> <div class="form_row"> <div class="primary_row subexists">1</div> <div class="primary_row_sub subexists">1a</div> <div class="secondary_row subexists">2</div> <div class="secondary_row_sub">2a</div> </div> 

I am in the process of creating it now, so this is still a draft, but its safe adoption of more classes will exist on different elements depending on the need. The four main classes I'm worried about are primary_row, primary_row_sub, secondary_row, secondary_row_sub . I create a click handler, for example:

 $('.form_row > div').click(function() { //code }); 

in this click handler, I want to determine if the item was clicked is one of the four mentioned above. If so, I want to do something based on what. Thus, determining which class belongs to an element, clicked rather than built four click handlers, one for each type. I hope that I can keep it optimized and keep it in one handler. Any ideas?

+4
source share
2 answers

One option:

 var classMap = {"one": function () { alert("one");}, "two": function () { alert("two");}, "three": function () { alert("three");} } , classes = ""; $('div').click(function (e) { classes = this.className.split(" "); for (key in classMap) { if ($.inArray(key, classes) !== -1) { classMap[key](); } } }); 

http://jsfiddle.net/wp9X7/5/

+1
source
 if ($(this).is(".primary_row")) { ... } elseif ($(this).is(".primary_row_sub")) { ... } and so on 
0
source

All Articles