首页 > 解决方案 > jQuery - 变量而不是表 id

问题描述

如何使用变量而不是表 id?

例如,我想将 id 替换#myTable为变量table

function findFruitColor(table, fruit) {


  let colKey = $("#myTable th:contains('Fruit')").index();
  let colVal = $("#myTable th:contains('Color')").index();

  $('#myTable tr td:nth-child(' + (colKey + 1) + ')').each(function() {

    if ($(this).text() === fruit) {
      color = $(this).siblings('td').addBack().eq(colVal).text();
      return false;
    }

  })


  // Display the color that was found 
  if (typeof color !== 'undefined') {
    console.log("The color for " + fruit + " is " + color);
  }


}

// Call the function
findFruitColor("#myTable", "apple");
th {
  font-weight: bold;
  width: 11em;
  text-align: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table id="myTable">
  <tr>
    <th>Fruit</th>
    <th>Color</th>
  </tr>
  <tr>
    <td>apple</td>
    <td>red</td>
  </tr>
  <tr>
    <td>banana</td>
    <td>yellow</td>
  </tr>

在 jsFiddle 上查看

标签: javascriptjqueryhtml-tabledatatable

解决方案


现代方式

使用模板文字

let colKey = $(`${table} th:contains('Fruit')`).index();

模板文字为您节省了很多关于转义引号字符的麻烦。在此处查找对此的浏览器支持。

旧方法(您已经在代码示例中使用):

使用字符串连接:

let colKey = $(table + " th:contains('Fruit')").index();

推荐阅读