如何在td中添加Class如果在表中重复数据

时间:2017-02-10 17:24:19

标签: javascript jquery

如何添加类相同的记录?

<table>
    <tr>
        <td>ID</td>
        <td>Name</td>
    </tr>
    <tr>
        <td>1</td>
        <td>haris</td>
    </tr>
    <tr>
        <td>2</td>
        <td>ali</td>
    </tr>
    <tr>
        <td>3</td>
        <td>haris</td>
    </tr>


 </table>

如何添加类或如何在此重复记录中添加样式?

1 个答案:

答案 0 :(得分:0)

迭代所有tr并过滤掉用于应用类的重复tr。

// object for refering text
var obj = {};

// get all tr except the first one which holds header
$('table tr:not(:first-child)').filter(function() {
  // get td contents and trim out space
  var txt = $('td:last-child', this).text().trim();
  // check already defined in object or not
  if (txt in obj)
  // if defined return true, it's dupe
    return true;
  // else define the property
  obj[txt] = true;
  // add class to filtered tr
}).addClass('dup')

.dup {
  color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>ID</td>
    <td>Name</td>
  </tr>
  <tr>
    <td>1</td>
    <td>haris</td>
  </tr>
  <tr>
    <td>2</td>
    <td>ali</td>
  </tr>
  <tr>
    <td>3</td>
    <td>haris</td>
  </tr>
</table>

</table>
 <script>
                            $(document).ready(function () {
                                $('img').on('click', function () {
                                    var image = $(this).attr('src');
                                    $('#myModal').show('show.bs.modal', function () {
                                        $(".showimage").attr('src',image);
                                    });
                                });
                            });
                        </script>