javascript - 如何在模板文字 js 表达式中选择 $(this)?
问题描述
我知道每次我在函数内部调用“this”时,它都会选择在参数中给出的任何选择器,但是如何使用这样的模板文字并获取在 append 方法中生成的行的索引?
$(document).on('click', '.add-row', function () {
$(this).closest("table").find("tbody").append(`
<tr>
<td> ${ $(this).closest("tr").index() } </td>
</tr>
`)
});
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" integrity="sha384-skAcpIdS7UcVUC05LJ9Dxay8AXcDYfBJqt1CJ85S/CFujBsIzCIv+l9liuYLaMQ/" crossorigin="anonymous"></script>
</head>
<body>
<table class="table table-bordered">
<thead>
<th>INDEX</th>
<th>SOMETHING</th>
<th><button class="btn btn-primary add-row">ADD ROW</button></th>
</thead>
<tbody></tbody>
</table>
</body>
</html>
解决方案
您需要找到 tbody,并查看该元素的子元素数量以获取计数器:
$(document).on('click', '.add-row', function () {
var $tbody = $(this).closest("table").find("tbody");
$tbody.append(`
<tr>
<td> ${ $tbody.children().length } </td>
</tr>
`)
});
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.min.js" integrity="sha384-skAcpIdS7UcVUC05LJ9Dxay8AXcDYfBJqt1CJ85S/CFujBsIzCIv+l9liuYLaMQ/" crossorigin="anonymous"></script>
</head>
<body>
<table class="table table-bordered">
<thead>
<th>INDEX</th>
<th>SOMETHING</th>
<th><button class="btn btn-primary add-row">ADD ROW</button></th>
</thead>
<tbody></tbody>
</table>
</body>
</html>
推荐阅读
- spring-cloud - 在 zipkin 中记录消息
- python - 为什么 Python 中协方差函数的输出相差太大?
- jvm - 使用 OpenJ9 的类数据共享时,应该对 JVM 内存的哪个区域影响最大
- google-analytics - 在 BigQuery 中为自定义维度复制 Google Analytics 所有会话
- php - iframe-curl 内容盗窃
- java - 有没有办法使用意图打开特定组(家庭应用程序、电话应用程序)的默认应用程序屏幕?
- php - 在 PHP 语句中更改文本框的值
- bash - 按下向上箭头并更改 bash 提示后,文本破碎
- php - 从 PHP SOAP 响应解析 XML 数据
- sql - 使用带有过滤器的 Union 创建重复项