当没有类或id直接选择它们时,向表头元素添加类

时间:2016-09-14 14:14:41

标签: jquery

我有下表

FILETIME

我正在尝试为每个struct.unpack添加不同的属性。理想情况下使用jquery .index和.attr

如果没有ID或类,请不确定如何选择<table class="results"> <thead> <tr> <th>Title1</th> <th>Title2</th> </tr> </thead> <tbody> <tr> <td>a</td> <td>e</td> </tr> <tr> <td>b</td> <td>f</td> </tr> <tr> <td>c</td> <td>g</td> </tr> <tr> <td>d</td> <td>h</td> </tr> </tbody>

我猜我们可以使用.results类吗?

2 个答案:

答案 0 :(得分:1)

  

我想为第2个添加不同的属性,例如th = =#34;一个&#34; th = =#34;两个&#34;

要实现这一点,您可以使用映射到表中th元素的索引的类名数组。试试这个:

&#13;
&#13;
var classes = ['one', 'two'];
$('.results th').addClass(function(i) {
  return classes[i];
});
&#13;
.one {
  color: red;
}
.two {
  color: blue;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="results">
  <thead>
    <tr>
      <th>Title1</th>
      <th>Title2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>a</td>
      <td>e</td>
    </tr>
    <tr>
      <td>b</td>
      <td>f</td>
    </tr>
    <tr>
      <td>c</td>
      <td>g</td>
    </tr>
    <tr>
      <td>d</td>
      <td>h</td>
    </tr>
  </tbody>
</table>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

试试这个:

$(document).ready(function(){

    $("th").each(function(index,ele){

        var cla = (index===0) ? "one" : "two";

        $(this).addClass(cla);

    })
})

最终代码:

&#13;
&#13;
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
        .one {
            color: red;
        }
        .two {
            color: blue;
        }
    </style>
</head>
<body>
    <table class="results">
<thead>
  <tr>
    <th>Title1</th>
    <th>Title2</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td>a</td>
    <td>e</td>
  </tr>
  <tr>
    <td>b</td>
    <td>f</td>
  </tr>
  <tr>
    <td>c</td>
    <td>g</td>
  </tr>
  <tr>
    <td>d</td>
    <td>h</td>
  </tr>
</tbody>
    </table>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>
$(document).ready(function(){
    
    $("th").each(function(index,ele){
        
        var cla = (index===0) ? "one" : "two";
        
        $(this).addClass(cla);
            
    })
})
       
    </script>
</body>
</html>
&#13;
&#13;
&#13;