【问题标题】:jQuery table on click for rows grabs table headers aswell点击行的jQuery表格也可以抓取表格标题
【发布时间】:2017-12-14 03:12:51
【问题描述】:

我的 vue 应用程序中有一个功能,当单击此处的表格行时完成:

$("#connectionsTable tr").click(function () {
  var list = [];
  var $row = $(this).closest("tr"),
  $tds = $row.find("td");
  // console.log($tds);
  // list.push({ name: $tds.eq(0).text(), numSongs: $tds.eq(1).text(), Year: $tds.eq(2).text() });
  list.push({ connectionName: $tds.eq(0).text(), host: $tds.eq(1).text(), port: $tds.eq(2).text(), serviceName: $tds.eq(2).text() });
   // self.$store.state.tableRow = list;
   self.setConnectionTableRow(list);
   self.$router.push('/analytic-two');
});

有没有办法我可以编写排除表头作为点击功能之一的函数,任何帮助将不胜感激,谢谢。

【问题讨论】:

  • 根据 HTML 规范,您的表格标题行位于 thead 中,对吧?
  • $("#connectionsTable tbody tr") 会做,假设你已经在 thead 中包装了标题
  • 您能否也向您展示模板代码,因为您可以通过仅在<tr> 元素上设置点击侦听器来以 vuejs 的方式进行操作

标签: jquery vue.js


【解决方案1】:

是的,请确保您的表头在正确的thead 中并且正文在tbody 中,然后选择器就变成了:

$("#connectionsTable tbody tr").click(function () { ... } )

下面的实例。

$('table tbody tr').click(function(){
    console.log("click on body");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
  <th>Header1</th>
</tr>
</thead>
<tbody>
<tr>
  <td>Cell</td>
</tr>
</tbody>
</table>

【讨论】:

    【解决方案2】:

    向标题行添加一个类,如class="header-row",并在检查该行后添加return false hasClass() header-row 喜欢,

    $("#connectionsTable tr").click(function () {
       if($(this).hasClass('header-row'))
          return false; // getting header row, so return from here without executing other statements
       var list = [];
       ....
    });
    

    或者,您可以使用 :not() like 排除标题行,

    $("#connectionsTable tr:not(.header-row)").click(function () {
       var list = [];
       ....
    });
    

    【讨论】:

    • 如果您对该元素不感兴趣,为什么不直接将tr:not(.header-row) 用作选择器?
    • $("#connectionsTable tr:not(.header-row)") 会是更好的选择器
    猜你喜欢
    • 1970-01-01
    • 2012-07-04
    • 1970-01-01
    • 2020-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多