jQuery学习笔记 - 2 简单的表格操作

本文介绍如何使用jQuery从HTML表格中提取特定数据。包括获取指定单元格的值、获取某一列的所有值以及获取某一行的所有值的方法。

我使用的jQuery版本为jquery-3.3.1.js,下载地址:https://code.jquery.com/jquery-3.3.1.js

我使用的Chrome版本为 Version 63.0.3239.132 (Official Build) (64-bit)

给定一个表格如下图所示:

实现三个功能:

1、获取第二行第三列值(B3)

2、获取第三列所有的值(A3、B3、C3、D3、E3)

3、获取第三行所有的值(C1、C2、C3、C4)

代码如下:

<html>
  <head>
    <title>jQuery学习</title>
    <!--表格处理-->
  </head>
  <body>
    <table border="1" id="tbl">
      <tr>
        <th></th>
        <th>第一列</th>
        <th>第二列</th>
        <th>第三列</th>
        <th>第四列</th>
      </tr>
      <tr><td>第一行</td><td>A1</td><td>A2</td><td>A3</td><td>A4</td></tr>
      <tr><td>第二行</td><td>B1</td><td>B2</td><td>B3</td><td>B4</td></tr>
      <tr><td>第三行</td><td>C1</td><td>C2</td><td>C3</td><td>C4</td></tr>
      <tr><td>第四行</td><td>D1</td><td>D2</td><td>D3</td><td>D4</td></tr>
      <tr><td>第五行</td><td>E1</td><td>E2</td><td>E3</td><td>E4</td></tr>
    </table>
    <br>
    <button type="button" id='btnGetValue'>获取第二行第三列值</button><br>
    <button type="button" id='btnGetValue2'>获取第三列所有的值</button><br>
    <button type="button" id='btnGetValue3'>获取第三行所有的值</button><br>
    <script src="jquery-3.3.1.js"></script>
    <script>

      $(function(){

        //目标1:获取第2行第3列的值
        $('#btnGetValue').click(function(){
          var val = $("#tbl tr:eq(2) td:eq(3)").html();
          alert(val);
        })

        //目标2:获取第三列所有的值
        $('#btnGetValue2').click(function(){
          $("#tbl tr:gt(0)").each(function(){
            alert($(this).children("td").eq(3).html());
          })
          /* 以下代码功能同上
          $("#tbl tr").each(function(i){
            if(i>=1){
              alert($(this).children("td").eq(3).html());
            }
          })*/
        })
        
        //目标3:获取第三行所有的值
        $('#btnGetValue3').click(function(){
          $("#tbl tr:eq(3) td:gt(0)").each(function(){
            alert($(this).html());
          })
        })
        
      });

    </script>
  </body>
</html>

END

转载于:https://my.oschina.net/Tsybius2014/blog/1622978

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值