jquery - 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>
解决方案
创建一个函数,例如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>
推荐阅读
- c++ - 使用 MPI 发送二维数组
- excel - 调试从 Access 宏调用的 Excel 宏
- alfresco - 我可以使用什么 REST API 在记录管理站点中记录文件或文件夹
- ios - 为什么 Swift Int 零在 objc 代码中被读取为零?
- php - Laravel 试图获取非对象的属性“project_name”
- java - 存储一个变量,以便下次访问该类时它是相同的
- sql - 想根据星期五做一个条件
- android - Volley to Room SQLite 与现有的主键
- bash - 如何使用 docker-compose 为非 root 用户设置环境变量?
- reactive-programming - 如何以非常通用的方式将有效负载响应式发送到 Kafka 主题?