首页 > 解决方案 > 使用 jQuery 检查表是否具有属性值

问题描述

我正在尝试在窗口调整大小和加载时显示内容。之后单击table th属性等于给定值。我不知道我在哪里做错了,但我无法得到结果。

$(window).on("load resize", function(e) {
  var $theWindowSize = $(this).width();
  if ($theWindowSize < 768) {
    alert($theWindowSize);
    if ($('table th').attr('id') == 'basic-tab') {
      $('table th#basic-tab').on('click', function(e) {
        alert('basic');
        $('table .basic-content').css('display', 'block');
      });
    } else if ($('table th').attr('id') == 'standard-tab') {
      $('table th#standard-tab').on('click', function(e) {
        alert('standard');
        $('table .standard-content').css('display', 'block');
      });
    }
  }
});
.basic-content,
.standard-content {
  dispaly: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <th id="basic-tab">Tab1</th>
    <th id="standard-tab">Tab2</th>
  </tr>
  <tr class="basic-content">
    <td>Basic Content</td>
  </tr>
  <tr class="standard-content">
    <td>Standard Content</td>
  </tr>
</table>

标签: jqueryhtmlcss

解决方案


单击th获取id,将其拆分并获取第一部分,然后检查哪个tr包含class从此开始string并包含content。在上面应用 CSS

工作片段: -

$('table th').on('click',function(e){
  var thId = $(this).attr('id');
  var compare = thId.split('-')[0];
  $('tr').each(function(){
      if($(this).attr('class') != undefined){
        $(this).css('display','none');
      }
  });
  $('tr[class*='+compare+'-content]').css('display','block');
});
.basic-content,.standard-content{
  display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <th id="basic-tab">Tab1</th>
    <th id="standard-tab">Tab2</th>
  </tr>
  <tr class="basic-content">
    <td>Basic Content</td>
  </tr>
  <tr class="standard-content">
    <td>Standard Content</td>
   </tr>
</table>

注意:-根据您的 HTMLcontent在代码中添加。$('tr[class*='+compare+'-content]')如果您需要将 CSS 添加到所有包含basicstandered在其中的类中,请content从代码中删除并制作它 $('tr[class*='+compare+'-]')


推荐阅读