18910140161

JavaScript-如何在模板文字JS表达式中选择$(this)?-堆栈溢出

顺晟科技

2022-10-18 12:59:27

72

我知道每次我叫“这个”在函数内部,它将选择在参数中给出的任何选择器,但是如何使用这样的模板文字并获得在append方法中生成的行的索引呢?

$(document).on('click', '.add-row', function () {
  $(this).closest("table").find("tbody").append(`
     <tr>
       <td> ${ $(this).closest("tr").index() } </td>
    </tr>
  `)
});
<代码><;HTML(>;)<;头部>;<;script SRC=“ https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js ”>;<;/script>;<;link rel=“ stylesheet ” href=“ UNK1@5.1.1/dist/CSS/bootstrap.min.CSS ” integrity=“ sha384-f3w7mx95pdgytmzzmecangseqb83dfgtowi0imjiwaevhan4fjkqjbyhzmi3ahiu ” crossorigin=“ anonymous ”>;<;script SRC=“ UNK1@5.1.1/dist/JS/bootstrap.min.JS ” integrity=“ sha384-skacpids7ucvuc05lj9dxay8axcdyfbjqt1cj85s/cfujbsizciv+l9liuylamq/” crossorigin=“ anonymous ”>;<;/script>;<;/标题>;<;身体>;<;表类=“表表边界”>;<;头(>;)<;th>;索引<;/th>;<;th>;某事<;/th>;<;TH>;<;BUTTON CLASS=“ btn btn-primary add-row ”>;添加行<;/BUTTON>;<;/TH>;<;/thead>;<;tbody>;<;/tbody>;<;/表格>;<;/正文>;<;/HTML>;


顺晟科技:

您需要找到tbody,并查看该元素的子元素的数量以获得计数器:

<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>
<代码><;HTML(>;)<;头部>;<;script SRC=“ https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js ”>;<;/script>;<;link rel=“ stylesheet ” href=“ UNK1@5.1.1/dist/CSS/bootstrap.min.CSS ” integrity=“ sha384-f3w7mx95pdgytmzzmecangseqb83dfgtowi0imjiwaevhan4fjkqjbyhzmi3ahiu ” crossorigin=“ anonymous ”>;<;script SRC=“ UNK1@5.1.1/dist/JS/bootstrap.min.JS ” integrity=“ sha384-skacpids7ucvuc05lj9dxay8axcdyfbjqt1cj85s/cfujbsizciv+l9liuylamq/” crossorigin=“ anonymous ”>;<;/script>;<;/标题>;<;身体>;<;表类=“表表边界”>;<;头(>;)<;th>;索引<;/th>;<;th>;某事<;/th>;<;TH>;<;BUTTON CLASS=“ btn btn-primary add-row ”>;添加行<;/BUTTON>;<;/TH>;<;/thead>;<;tbody>;<;/tbody>;<;/表格>;<;/正文>;<;/HTML>;

  • TAG:
相关文章
随机推荐
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航