【问题标题】:jQuery - variable instead of table idjQuery - 变量而不是表 id
【发布时间】:2020-04-16 22:31:13
【问题描述】:

如何使用变量而不是表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>

View on jsFiddle

【问题讨论】:

  • $(table).find("tr ...")... (另外,如果 table 是字符串格式的 id,您可以随时使用 $(table + " th ...") 但这不是好的做法)
  • @ChrisG 谢谢,但不完全是。你的评论和答案都更清楚了。也许这个问题特定于 find() 方法。例如,从硬编码的 tableID——$("#id tr...") 到这里看到的变量——$(table).find("tr...") 需要我们添加 .find()。那是缺失的部分。

标签: javascript jquery html-table datatable


【解决方案1】:

现代方式

使用template literals:

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

模板字面量为您省去了很多关于引号字符转义的麻烦。查找此here 的浏览器支持。

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

使用字符串连接:

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

【讨论】:

    猜你喜欢
    • 2017-01-28
    • 2011-07-01
    • 2011-01-11
    • 2011-04-14
    • 1970-01-01
    • 1970-01-01
    • 2022-12-22
    • 2016-12-25
    • 1970-01-01
    相关资源
    最近更新 更多