如何使用Jquery获取表中的每个td包含

时间:2011-08-11 03:14:37

标签: jquery jquery-ui jquery-selectors

我正在动态生成一个表。

我想获取所有的TD内容,不包括Thead内容。

我的表看起来像这样:

<Html>
<table id="tblPhone">
  <thead>
    <tr>
      <th> Type </th>
      <th> Primary </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td> Gen </td>
      <td> <input type="radio" CHECKED /> </td>
    </tr>
    <tr>
      <td> Mob </td>
      <td> <input type="radio" /> </td>
    </tr>
....
....
  </tbody>
</table>
</Html>

我需要获取数据&amp;填写我的下面的课程(C#):

class TelephoneType
{
  public string Type;
  public bool Primary;
}

我在按钮点击中使用了下面的JS功能,但它不起作用:(。

function RetriveTelephoneData() {

    var obj = $("#tblPhone");

    var hasTH = obj.find("thead").size() > 0;
    var hasTBody = obj.find("tbody").size() > 0;

    if (obj.is("table") && !hasTH) {
        var widths = [];

        // capture widths before rearranging
        obj.find("tr td").each(function(i) {
            widths.push($(this));
        });
    }
}

我是Jquery的新手。请帮我解决这个问题。 Thx提前。

3 个答案:

答案 0 :(得分:1)

尝试将此作为按钮点击代码:

function Telephone(type,primary)
{
    this.Type=type;
    this.Primary=primary
}

function RetriveTelephoneData(){
    var phones=[];
    $("table#tblPhone > tbody > tr").each(function(){
    var tds=$(this).find("td");
    var t=new Telephone($(tds[0]).text(), $(tds[1]).find("input:radio").is(":checked"));
    phones.push(t);
}

首先创建一个js类来捕获值。接下来循环遍历tbody中的所有行,找到type' and主要value of phone to create object of Telephone`类并将其推送到数组。现在,您可以使用数组的内容做任何您喜欢的事情。

PS: - 你需要在你的单选按钮上添加name属性(与name='primary'相同的值。

答案 1 :(得分:0)

请勿在{{1​​}}使用<td>中使用<thead>

<th>

等...

<table>
  <thead>
    <tr>
       <th>Column1</th>
       <th>Column2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
       <td> 0,1</td>
       <td> 1,1</td>
    </tr>
  </tbody>
</table>

答案 2 :(得分:0)

试试这个

function RetriveTelephoneData() {

    //var obj = $("#tblPhone");

    //var hasTH = obj.find("thead").size() > 0;
    //var hasTBody = obj.find("tbody").size() > 0;

    //if (obj.is("table") && !hasTH) {
        var widths = [];

        // capture widths before rearranging
        $("#tblPhone").find("td").each(function(i) {
            widths.push($(this).width());
        });
    //}
}