首页 > 解决方案 > 如何在模板文字 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>

标签: javascripthtmljquery

解决方案


您需要找到 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>


推荐阅读