Jonnny Jonnny - 1 month ago 16
jQuery Question

JQuery compare class names

I'm not sure what I've done wrong in this. I have assigned classes dynamically to rows. These classes are ordered and a row can have the same class. I want to order all the classes with multiple of the same identifier one colour. Then the next set of numbers an alternative colour before going back to the original colour. The last row always seems to fail though.

<body>
<table>
<thead>Row</thead>
<tbody>
<tr class="a-1"><td>A1 row</td></tr>
<tr class="a-2"><td>A2 row</td></tr>
<tr class="a-2"><td>A2 row</td></tr>
<tr class="a-2"><td>A2 row</td></tr> // should have class warning,but doesn't after js
<tr class="a-3"><td>A3 row</td></tr>
<tr class="a-4"><td>A4 row</td></tr>
<tr class="a-4"><td>A4 row</td></tr>
<tr class="a-4"><td>A4 row</td></tr>
<tr class="a-4"><td>A4 row</td></tr> // should have class warning,but doesn't after js
</tbody>
</table>
</body>


JQuery

var flag = true;
$("table tr[class^='a-']").each(function(){
var current = $(this);
if((current.attr("class") == current.next().attr("class")) || (current.attr("class") == current.prev().attr("class"))){
if(flag){
current.addClass("info");
} else {
current.addClass("warning");
}
} else {
if(flag){
flag = false;
} else {
flag = true;
}
}
});


I made a jsfiddle to show my problem

Answer

$(function() {
  var flag = true;
  $("table tr[class^='a-']").each(function() {
  
    var current = $(this);
    var next = current.next();
    var prev = current.prev();

    var currentClassName = $(this).attr('class');
   // alert(currentClassName);
   if(next.hasClass(currentClassName) || prev.hasClass(currentClassName))
   {
      if(flag){
          current.addClass("info");
        } else {
          current.addClass("warning");
        }
   }
     else {
        if(flag){
          flag = false;
        } else {
          flag = true;
        }
    }
  });
});
.info{background-color: blue;}
.warning{background-color: yellow;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <table>
    <thead>Row</thead>
    <tbody>
      <tr class="a-1">
        <td>A1 row</td>
      </tr>
      <tr class="a-2">
        <td>A2 row</td>
      </tr>
      <tr class="a-2">
        <td>A2 row</td>
      </tr>
      <tr class="a-2">
        <td>A2 row</td>
      </tr>// should have class warning,but doesn't after js
      <tr class="a-3">
        <td>A3 row</td>
      </tr>
      <tr class="a-4">
        <td>A4 row</td>
      </tr>
      <tr class="a-4">
        <td>A4 row</td>
      </tr>
      <tr class="a-4">
        <td>A4 row</td>
      </tr>
      <tr class="a-4">
        <td>A4 row</td>
      </tr>// should have class warning,but doesn't after js
    </tbody>
  </table>
</body>

Hope this helps

Comments