我如何获得特定值?

时间:2011-06-01 01:08:42

标签: jquery html

我面临着jQuery和HTML元素的麻烦。 让我们来到“艺术家”:

<table id="tableBenef" width="375px">
     <tr style="border-bottom: solid 1px silver;">
         <td style="width: 10%"> Action </td>
         <td style="width: 45%"> Nome   </td>
         <td style="width: 20%"> Data Nasc </td>
         <td style="width: 25%"> Grau Parent </td>
     </tr>
</table>

以上就是表头和内部我添加了新的行。每行包含一个复选框和另外三个TD,我也有三个文本输入,我将每个输入发送到指示TD,复选框用于删除目的。

问题是,如何使用jQuery以新的方式插入这些新值?! 我从下面的代码开始:

 function getRowValues() {
            var table = $("#tableBenef");
            $(table).each(function () {
                alert($(this).text());
            })
        };

但是我遇到了麻烦,有人可以帮我吗?

在否定的情况下,无论如何,谢谢! 对不起任何错误。

2 个答案:

答案 0 :(得分:1)

廉价的解决方案:根本不要从HTML中取回它们。相反,在将每行插入HTML之前,将该行的值存储在数组中。然后,只需读取数组,而不必一直回到DOM。

根据要求,这里有一些非常基本的代码,介绍如何执行此操作。 (显然,这只是用来说明一般概念的代码,因为我不知道你的实际设置。)

var insertedRowData = [];

function insertRow(rowValues) {
  // I'm assuming that rowValues is in the form {key1: "value1", key2: "value2"}.
  // That sort of generic object is probably a good format for storage,
  // but it doesn't matter what format you use, so long as it is a single object
  // that can be stored now and accessed later.

  insertedRowData[insertedRowData.length] = rowValues;

  /*
    ...
    Insert the row into the table, like you're already doing.
    ...
  */
}

function handleRowValues() {
  // Hey, look! All of the data is still stored in insertedRowData.
  // I can now handle it in whatever way I want. I think I'll log them
  // to Chrome or Firebug's console, but you can do whatever you want here.

  console.log(insertedRowData);
}

答案 1 :(得分:1)

您正在桌面上应用.each(),而不是在单元格上。您需要添加获取特定后代的方法(在本例中为表格单元格)。这样做(jsfiddle):

function getRowValues() {
    var table = $("#tableBenef");
    $(table).find('td').each(function () {
        alert($(this).text());
    })
};

请注意额外的.find('td')正是我所描述的。

有用吗?