Javascript 如何在jquery表中通过onclick获得一些数据列和标题

Javascript 如何在jquery表中通过onclick获得一些数据列和标题,javascript,jquery,ajax,Javascript,Jquery,Ajax,现在我有了一个使用javascript生成的表。下面是我生成表的代码: $.ajax({ type:"POST", url:"../cdc/load/jsonTrack.php?", data:dataString, dataType: 'json', success: function(data){ if(data.status === "su

现在我有了一个使用javascript生成的表。下面是我生成表的代码:

$.ajax({
            type:"POST",
            url:"../cdc/load/jsonTrack.php?",
            data:dataString,
            dataType: 'json',
            success: function(data){
                if(data.status === "success") { 
                    var elements = data.elements; 
                    if(elements.length === 0) {
                        $('#cdcTracking-list tbody').append( '<tr>' +
                            '<td colspan="7">No session to display</td>' +
                            '</tr>');
                    }
                    for( var i = 0; i < elements.length; i++){
                        var element = elements[i];

                        //console.log('session id:' + element.vesselCode);
                        $('#cdcTracking-list tbody').append( '<tr>' +
                            '<td style="color: green;">' + element.vesselCode + '</td>' +
                            '<td style="color: black;">' + element.voyage + '</td>' +
                            '<td style="color: black;">' + element.chasisNo + '</td>' +
                            '<td style="color: black;">' + element.chasisNo + '</td>' +
                            '<td style="color: blue;">' + element.plateNo + '</td>' +
                            '<td style="color: blue;">' + element.bookingRef + '</td>' + 
                            '<td style="color: blue;">' + element.serviceTerm +'</td>'+
                            '</tr>'                                    
                        );
                    }
                }else { 
                    $('#cdcTracking-list tbody').append( '<tr><td colspan="7">No session to display</td></tr>');
                }
            }
        }); 

有没有人有这方面的经验,请帮我解决一下

您需要使用委派。因为加载dom时,没有这样的表数据。表是在DOM加载后通过ajax调用创建的

$(document).on("click", "#cdcTracking-list tr td", function() {
    var header = $('#cdcTracking-list th').eq($(this).index()).text(); //to get clicked column's header
        var trackid = $(this).siblings('td:nth-child(36)').text(); //get column at column 36
        var date = $(this).text(); //get clicked column value
});
如果源于DOM的初始加载(如下面所示),您还可以将目标指向祖先(#cdcTracking list)而不是文档

$('#cdcTracking-list').on("click","tr td",function(){
//code
}); 

在创建图元时将“单击”事件附加到图元:

$('<td>').on('click', doClick);
$(“”).on('click',doClick);
以下是一个经过清理和注释的版本,以说明:

// This is used a lot, we should keep a reference for cleaner code.
var $table = $('#cdcTracking-list tbody');

// No need to repeat the same pattern of code so we will use JS to iterate over
// code by telling it the values we want in each iteration. This is used for the
// makeElementTR helper function.
var dataKeys = [
  {prop: 'vesselCode',  color: 'green'},
  {prop: 'voyage',      color: 'black'},
  {prop: 'chasisNo',    color: 'black'},
  {prop: 'chasisNo',    color: 'black'}, // This is repeated, Why?
  {prop: 'plateNo',     color: 'blue'},
  {prop: 'bookingRef',  color: 'blue'},
  {prop: 'serviceTerm', color: 'blue'}
];

function onElementClick(e) {
  var header  = $('#cdcTracking-list th').eq($(this).index()).text(); //to get clicked column's header
  var trackid = $(this).siblings('td:nth-child(36)').text(); //get column at column 36
  var date    = $(this).text(); //get clicked column value
  // Do something with this?
}

// Making helper functions can make code further down easier to understand
function makeElementTR(element) {
  var $tr = $('<tr>');
  $.each(dataKeys, function(index, dataKey) {
    var value = element[dataKey.prop];
    $('<td>')
    .on('click', onElementClick)
    .css({color: dataKey.color})
    .text(value)
    .appendTo($tr);
  });
  return $tr;
}

$.ajax({
  type: 'POST',
  url: '../cdc/load/jsonTrack.php',
  // I hope this is not a normal string. That would be weired.
  data: dataString,
  // How come your PHP script can't set the 'Content-Type: application/json'?
  // If it did you wouldn't need this.
  dataType: 'json'
})

// Using success callbacks, especially when defined in-line, is really hard to
// read. Use jQuery's promise-like syntax for more readability and flexibility.
.then(function(data) {
  var elements = data.elements;

  // Don't repeat yourself, If your going to respond the same with either
  // success !=== 'success' or no elements put them both in the same if
  // statement.
  if (data.success !== 'success' || elements.length === 0) {

    // Wait a second, if the code reaches here then that means the PHP script
    // returned a 200 (Success/Happy) response except the data.success is
    // telling the you the server lied? It would be easier to have the PHP
    // script return an error response instead of a success response here.
    // However, if that isn't possible then we will fake that is what happened
    // by throwing our own exception which will be passed on as if the server
    // said as much.
    throw "No session to display"; // Let someone else handle this.
  }

  $.each(elements, function(index, element) {
    makeElementTR(element)
    .appendTo($table);
  });
})

// This guy knows what to do when things are not working the way we want.
.fail(function(reason) {
  if (typeof reason === 'string') {
    $('<tr>')
    .append($('<td>', {colspan: 7}).text(reason))
    .appendTo($table);
  } else {
    alert('Oh no! Something bad happend: ' + reason); // coherce to string
  }
});
//这是经常使用的,我们应该为更干净的代码保留一个参考。
var$table=$(“#CDC跟踪列表tbody”);
//无需重复相同的代码模式,因此我们将使用JS在
//通过在每次迭代中告诉它我们想要的值来编码。这是用于
//makeElementTR辅助函数。
var数据键=[
{prop:'vesselCode',颜色:'green'},
{道具:“航行”,颜色:“黑色”},
{道具:'chasisNo',颜色:'black'},
{prop'chasisNo',color'black'},//这是重复的,为什么?
{道具:'plateNo',颜色:'blue'},
{道具:'bookingRef',颜色:'blue'},
{prop:'serviceTerm',颜色:'blue'}
];
函数onElementClick(e){
var header=$('#cdcTracking list th').eq($(this.index()).text();//以获取单击的列标题
var trackid=$(this).sibbins('td:nth child(36)').text();//在第36列获取列
var date=$(this).text();//获取单击的列值
//用这个做点什么?
}
//制作助手函数可以使代码更容易理解
函数makeElementTR(元素){
var$tr=$('');
$.each(数据键,函数(索引,数据键){
var值=元素[dataKey.prop];
$('')
.on('click',onElementClick)
.css({color:dataKey.color})
.文本(值)
.appendTo($tr);
});
返回$tr;
}
$.ajax({
键入:“POST”,
url:“../cdc/load/jsonTrack.php”,
//我希望这不是一个普通的字符串。那会很奇怪。
数据:dataString,
//为什么PHP脚本不能设置“Content-Type:application/json”?
//如果是的话,你就不需要这个了。
数据类型:“json”
})
//使用成功回调,特别是在联机定义时,确实很难实现
//阅读。使用jQuery的promise-like语法可获得更高的可读性和灵活性。
.then(功能(数据){
var元素=data.elements;
//不要重复你自己的话,如果你想用同样的方式来回应
//成功!='success'或没有元素将它们放在同一个if中
//声明。
if(data.success!='success'| | elements.length==0){
//等一下,如果代码到达这里,那么这意味着PHP脚本
//返回了200(成功/满意)响应,数据除外。成功为
//告诉你服务器撒谎了吗?让PHP
//脚本在此返回错误响应,而不是成功响应。
//然而,如果这是不可能的,那么我们将假装这就是发生的事情
//通过抛出我们自己的异常,该异常将像服务器
//我也这么说。
抛出“无要显示的会话”;//让其他人处理此问题。
}
$.each(元素、函数(索引、元素){
makeElementTR(元素)
.附件($表);
});
})
//这家伙知道当事情没有按我们想要的方式进行时该怎么办。
.失败(功能(原因){
如果(原因类型=='string'){
$('')
.append($('',{colspan:7}).text(原因))
.附件($表);
}否则{
警惕(‘哦,不!发生了什么不好的事情:’+原因);//与字符串相关
}
});

这个答案仍然有很多重复的代码。为什么不将其干燥,然后在创建时将click事件附加到新创建的对象,而不是在创建后重新查询/过滤?
// This is used a lot, we should keep a reference for cleaner code.
var $table = $('#cdcTracking-list tbody');

// No need to repeat the same pattern of code so we will use JS to iterate over
// code by telling it the values we want in each iteration. This is used for the
// makeElementTR helper function.
var dataKeys = [
  {prop: 'vesselCode',  color: 'green'},
  {prop: 'voyage',      color: 'black'},
  {prop: 'chasisNo',    color: 'black'},
  {prop: 'chasisNo',    color: 'black'}, // This is repeated, Why?
  {prop: 'plateNo',     color: 'blue'},
  {prop: 'bookingRef',  color: 'blue'},
  {prop: 'serviceTerm', color: 'blue'}
];

function onElementClick(e) {
  var header  = $('#cdcTracking-list th').eq($(this).index()).text(); //to get clicked column's header
  var trackid = $(this).siblings('td:nth-child(36)').text(); //get column at column 36
  var date    = $(this).text(); //get clicked column value
  // Do something with this?
}

// Making helper functions can make code further down easier to understand
function makeElementTR(element) {
  var $tr = $('<tr>');
  $.each(dataKeys, function(index, dataKey) {
    var value = element[dataKey.prop];
    $('<td>')
    .on('click', onElementClick)
    .css({color: dataKey.color})
    .text(value)
    .appendTo($tr);
  });
  return $tr;
}

$.ajax({
  type: 'POST',
  url: '../cdc/load/jsonTrack.php',
  // I hope this is not a normal string. That would be weired.
  data: dataString,
  // How come your PHP script can't set the 'Content-Type: application/json'?
  // If it did you wouldn't need this.
  dataType: 'json'
})

// Using success callbacks, especially when defined in-line, is really hard to
// read. Use jQuery's promise-like syntax for more readability and flexibility.
.then(function(data) {
  var elements = data.elements;

  // Don't repeat yourself, If your going to respond the same with either
  // success !=== 'success' or no elements put them both in the same if
  // statement.
  if (data.success !== 'success' || elements.length === 0) {

    // Wait a second, if the code reaches here then that means the PHP script
    // returned a 200 (Success/Happy) response except the data.success is
    // telling the you the server lied? It would be easier to have the PHP
    // script return an error response instead of a success response here.
    // However, if that isn't possible then we will fake that is what happened
    // by throwing our own exception which will be passed on as if the server
    // said as much.
    throw "No session to display"; // Let someone else handle this.
  }

  $.each(elements, function(index, element) {
    makeElementTR(element)
    .appendTo($table);
  });
})

// This guy knows what to do when things are not working the way we want.
.fail(function(reason) {
  if (typeof reason === 'string') {
    $('<tr>')
    .append($('<td>', {colspan: 7}).text(reason))
    .appendTo($table);
  } else {
    alert('Oh no! Something bad happend: ' + reason); // coherce to string
  }
});