将整个表行数据提取到javascript变量中

时间:2013-10-28 17:40:34

标签: javascript php html css web

我有一个像这样的html表:

| name | type   | edit |
| zzz  | aaaa   | edit |
| xxx  | bbbb   | edit |
| mmm  | cccc   | edit |

所以,我想要做的是,如果我按第二行的编辑,我想要数据“xxx” 和“bbb”存储在一些javascript变量中以供进一步使用

我找到了这段代码。但它只会给我点击的单元格而不是整行

$('#tableID').click(function(e){
    alert($(e.target).text()); // using jQuery
})

更新 所以我的表格单元结构

<tr>
        <td> <?php echo $row['name'] ?> </td>
        <td> <?php echo $row['type'] ?></td>
        <td class="edit_button">Edit</td> 
</tr>

这是我用过它的JS

$("#table_id").on("click", ".edit_button", function() {
                    var data = $(this).closest("td").siblings().map(function() {
                    return $(this).text();
                }).toArray();
            }); 
            alert(data[0]);
            alert(data[1]);
            alert(data[2]);
}

2 个答案:

答案 0 :(得分:2)

$tr=$(e.target).closest("tr");

这会将表格行存储在变量中。

然后您可以使用以下方法访问每个td单元格:

$tr.find('td').each(function(){alert($(this).text())});

这是一个示例:http://jsfiddle.net/snowburnt/N85uA/

答案 1 :(得分:1)

我会使用事件委托而不是e.target。只需给你的编辑按钮一个类。

$("tableID").on("click", ".edit_button", function() {
    var data = $(this).closest("td").siblings().map(function() {
        return $(this).text();
    }).toArray();

    console.log(data);
});

现在data将使用edit按钮保存单元格的兄弟数组。


如果您不需要数组,但想直接在循环中使用文本,我会这样做。

$("tableID").on("click", ".edit_button", function() {
    $(this).closest("td").siblings().text(function(i, txt) {
        console.log(txt); // do something with the text
    });
});