jQuery从特定行中选择文本

时间:2012-11-19 07:15:53

标签: jquery

使用下表:

<table id="languages" border="0" cellspacing="1">
  <thead>
    <tr>
      <th>Language</th>
      <th>Type</th>
      <th>Invented</th>
    </tr>
  </thead>
  <tbody>
</tr>
    <tr>
      <td>Ruby</td>
      <td>Dynamic</td>
      <td>1993</td>
    </tr>    <table id="languages" border="0" cellspacing="1">
      <thead>
        <tr>
          <th>Language</th>
          <th>Type</th>
          <th>Invented</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Java</td>
          <td>Static</td>
          <td>1995</td>

    <tr>
      <td>Smalltalk</td>
      <td>Dynamic</td>
      <td>1972</td>
    </tr>
    <tr>
      <td>C++</td>
      <td>Static</td>
      <td>1983</td>
    </tr>
  </tbody>
</table>

如何从第三行中选择所有数据?我需要选择Smalltalk,Dynamic和1971.以下选择行。我需要数据。

    #languages tr:eq(3)

由于

2 个答案:

答案 0 :(得分:0)

只需使用

$('#languages tr:eq(3)').text()

获取全文

$('#languages tr:eq(3) td').map(function(){return $(this).text()}).toArray()

获取一系列文本:["Smalltalk", "Dynamic", "1972"]

但请注意,您的HTML有错误,而且您的行似乎位于'#languages tr:eq(2)',而不是'#languages tr:eq(3)'

Demonstration (open the console)

答案 1 :(得分:0)

将非标准属性放入tr标签:<tr key="1215">其中key s id在数据库表中,然后选择行和单元格:$('[key=3]').find('td').each(...工作样本http://jsbin.com/ofasin/1/

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<table id="languages" border="0" cellspacing="1">
  <thead>
    <tr>
      <th>Language</th>
      <th>Type</th>
      <th>Invented</th>
    </tr>
  </thead>
  <tbody>
    <tr key="1">
      <td>Ruby</td>
      <td>Dynamic</td>
      <td>1993</td>
    </tr>
    <tr key="2">
      <td>Java</td>
      <td>Static</td>
      <td>1995</td>
    </tr>
    <tr key="3">
      <td>Smalltalk</td>
      <td>Dynamic</td>
      <td>1972</td>
    </tr>
    <tr key="4">
      <td>C++</td>
      <td>Static</td>
      <td>1983</td>
    </tr>
  </tbody>
</table>  
  <script>
    var row = new Array();
    $('[key=3]').find('td').each(function(){
      row.push($(this).text());
    });
    alert('' + row);
  </script>
</body>
</html>