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

Get dynamic value every value of td of tr jquery

本文关键字:td jquery 动态 tr 获取      更新时间:2023-10-25
$("#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 请求中动态获取数据。我想知道如何通过单击类school_id来获取td的每个值。我想获取每个值并能够将其放入输入文本框中。点击id后最终结果会是这样的

var id = $('#tdwithidid').text();
var lastname = $('#tdwithidlastname').text();
var firstname = $('#tdwithidfirstname').text();
$('#id').val(id);
$('#lastname').val(lastname);
$('#firstname').val(firstname);
$(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);
    });

这将做你想做的事

由于您正在动态添加表,因此您需要这样的东西

$('#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
});
jQuery('.school_id').click(function (event){
    var theTd = jQuery(this).parent();
    var theId = theTd.attr('id');
});

像这样的东西?