获取tr jquery的td的每个值的动态值

时间:2015-02-14 12:11:14

标签: javascript jquery html html-table

$("#student").find("tr:gt(0)").remove();
for (var i = 0; i < data.length; i++) {
    tr = $('<tr/>');
    tr.append("<td id='id'>" + "<a class=\"school_id\"  id=" + data[i].id + " href='#' value='" + data[i].id + "'>" + data[i].id + "</a>" + "</td>");
    tr.append("<td id='lastname'>" + data[i].lastname + "</td>");
    tr.append("<td id='firstname'>" + data[i].firstname + "</td>");
    //$("#td_id").attr('width', '15%');
    //$('tr td:nth-child(1)').get(0).style.width = '100px';
    //tr.find('td:nth-child(2)').width('30%');‌​
    $("#student").append(tr);
}

我这里有一个代码,用一个学生名填充一个表。它从数据库的ajax请求中动态获取数据。我想知道如何通过点击课程td来获取school_id的每个值。我想获得每个值,并能够将其放在输入文本框中。点击id

后,最终结果将如下所示
var id = $('#tdwithidid').text();
var lastname = $('#tdwithidlastname').text();
var firstname = $('#tdwithidfirstname').text();

$('#id').val(id);
$('#lastname').val(lastname);
$('#firstname').val(firstname);

3 个答案:

答案 0 :(得分:1)

由于您要动态添加表格,因此您需要这样的内容

$('#student').on('click', '. school_id', function(e) {
    var parent = $(e.target).closest('tr'); //gets the parent tr element
    var id = parent.find('#id').html(); //finds element inside specific parent that has an id of id
    var lastName = parent.find('#lastname').html(); //finds element inside specific parent that has an id of last name
    var firstName = parent.find('#firstname').html(); //finds element inside specific parent that has an id of first name
});

答案 1 :(得分:1)

$(document).on('click', '#tableid tr', function(e) {
        var id = $(this).find('td:nth-child(1)').text();
        var lastname = $(this).find('td:nth-child(2)').text();
        var firstname = $(this).find('td:nth-child(3)').text();

        $('#id').val(id);
        $('#lastname').val(lastname);
        $('#firstname').val(firstname);
        console.log(tin + lastname + firstname);
    });

这将做你想要的事情

答案 2 :(得分:0)

jQuery('.school_id').click(function (event){
    var theTd = jQuery(this).parent();
    var theId = theTd.attr('id');
});

这样的东西?