首页 > 解决方案 > 如何在两个不同的表中使用 JQuery 更改 TH 的样式

问题描述

我有这个带有两个不同表格的 HTML:

<table class="mTabla" id="sdsdsdsf" style="margin: 0px auto; width: 100%; text-align: left; border-collapse: collapse;" border="1" rules="all" cellspacing="0">
  <tbody>
    <tr>
      <th style="display: none;" scope="col">#IdOculto</th>
      <th style="width: 200px;" scope="col">A1</th>
      <th style="width: 250px;" scope="col">A2</th>
      <th style="width: 200px;" scope="col">A3</th>
    </tr>
    
    <tr id="sdsdsds" style="cursor: pointer;">
      <td style="display: none;">57</td>
      <td>D1</td>
      <td>D1</td>
      <td>D1</td>
    </tr>
    
    <tr id="sdsdsds" style="cursor: pointer;">
      <td style="display: none;">58</td>
      <td>D2</td>
      <td>D2</td>
      <td>D2</td>
    </tr>       
  </tbody>
</table>    
    
<table class="mTabla" id="sdsdsd" style="margin: 0px auto; width: 100%; text-align: left; border-collapse: collapse;" border="1" rules="all" cellspacing="0">
  <tbody>
    <tr>
      <th style="display: none;" scope="col">#IdOculto</th>
      <th style="width: 200px;" scope="col">A1</th>
      <th style="width: 250px;" scope="col">A2</th>
      <th style="width: 200px;" scope="col">A3</th>
    </tr>
    
    <tr id="sdsdsds" style="cursor: pointer;">
      <td style="display: none;">57</td>
      <td>D1</td>
      <td>D1</td>
      <td>D1</td>
    </tr>
    
    <tr id="sdsdsds" style="cursor: pointer;">
      <td style="display: none;">58</td>
      <td>D2</td>
      <td>D2</td>
      <td>D2</td>
    </tr>       
  </tbody>
</table>

我需要使每个表的第一个可见 TH 元素具有边框半径。需要考虑的事情:我不能编辑 HTML 或 CSS 文件,我被要求只使用 JQuery 来做,我迷失了。表的 ID 不是代码中的 ID,但无论如何它们是动态的。

我的 jQuery 代码:

var testimonialElements = $(".mTabla");
for(var i = 0; i < testimonialElements.length; i++){
    $('th:visible:eq(0)').css("border-radius", "6px 0 0 6px");
}

这段代码部分满足了我的需要。它将我想要的样式应用于第一个可见的 TH mTable,但不会将其应用于第二个的第一个可见 TH mTable。我需要一个对两个表都有效的解决方案。我会很感激你的帮助。

标签: jquery

解决方案


这是将边框半径应用于两个表的第一个可见 TH 的方法。

$(".mTabla").each(function(){
    $(this).find('th:visible:eq(0)').css("border-radius","6px 0 0 6px");
})

I don't know if it is a good idea to add a border-radius to a TH element, but that isn't the question. :)


推荐阅读