首页 > 解决方案 > jQuery 用条件绑定元素可见性

问题描述

我在表格标题中有一个带有 id="data" 的按钮,只要表格行为 0,我想将其隐藏

我怎样才能将一些条件事件附加到按钮可见属性或类似的东西?

  <table class="table table-bordered table-striped table-sm">
                    <caption style="caption-side:top;">
                        <button onclick="getRandomLocalizacoesAjax()" class="btn btn-outline-secondary">
                            <i class="fas fa-sync-alt"></i>
                        </button>
                        <button id="data" onclick="insertRandomLocalizacoesAjax()" class="btn btn-outline-secondary">
                            <i class="fas fa-check"></i>
                        </button>
                    </caption>
                    <thead>
                        <tr>
                            <th>Localização</th>
                            <th>Etiquetas</th>
                        </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>

标签: jqueryhtml

解决方案


创建一个函数,例如toggleDataButton(),您可以在操作表行时调用该函数。您还可以在页面加载时调用该函数来设置初始状态。

您还将受益id="dataTable"于在表上设置一个 id(例如 )以便轻松查找。

const tableBody = $("#dataTable > tbody");

function toggleDataButton () {
  $("#data").toggle( tableBody.children().length !== 0 );
}

这是更改表格内容时如何调用函数的快速模型。单击同步按钮会将行追加到表中。单击垃圾桶按钮将清除表格。您的按钮将切换其可见性。

const tableBody = $("#dataTable > tbody");

// button visibility
function toggleDataButton () {
  $("#data").toggle( tableBody.children().length !== 0 );
}

// simulate appending table contents
function getRandomLocalizacoesAjax () {
  let r = () => Math.random().toString(36).substring(7)
  tableBody.append(`<tr>
    <td>${r()}</td>
    <td>${r()}</td>
  </tr>`);
  toggleDataButton();
}

// simulate clearing of table
function clearTable () {
  tableBody.empty();
  toggleDataButton();
}

// execute on dom ready
$(document).ready(function () {
  toggleDataButton();
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table id="dataTable" class="table table-bordered table-striped table-sm">
  <caption style="caption-side:top;">
    <button onclick="getRandomLocalizacoesAjax()" class="btn btn-outline-secondary"><i class="fas fa-sync-alt"></i></button>
    <button id="data" onclick="insertRandomLocalizacoesAjax()" class="btn btn-outline-secondary"><i class="fas fa-check"></i></button>
    <button id="clearData" onclick="clearTable()" class="btn btn-outline-secondary"><i class="fas fa-trash"></i></button>
  </caption>
  <thead>
    <tr>
      <th>Localização</th>
      <th>Etiquetas</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>


推荐阅读