简体   繁体   English

如何通过表jquery中的onclick获取一些数据列和标题

[英]how to get some data column and header by onclick in table jquery

Now I have a table that generate by using javascript .Below is my code to generate table : 现在我有一个使用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>');
                }
            }
        }); 

Does anyone know how can I get some column data and it header by onclick ,because my current code seem not working and I dont know if I'm missing something here.Below is my code to get : 有谁知道我如何通过onclick获得一些列数据及其标题,因为我当前的代码似乎无法正常工作,并且我不知道我是否在这里缺少什么。下面是我要获取的代码:

$('#cdcTracking-list tr td').click(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
});

Does anyone have a experience with this ,and please help me out 有人有经验吗,请帮帮我

You need to use delegation. 您需要使用委派。 because when dom is loaded there is no table data like this. 因为加载dom时没有这样的表数据。 Table is created after the DOM load by an ajax call. 通过ajax调用在DOM加载后创建表。

$(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
});

You can also target ancestor(#cdcTracking-list) instead of document if it was from the initial load of DOM like given below. 如果它是来自DOM的初始加载的,则您也可以定位祖先(#cdcTracking-list)而不是文档,如下所示。

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

Attach the click event to the element as you create them: 创建它们时,将click事件附加到元素上:

$('<td>').on('click', doClick);

Here is a cleaned up and commented version to illustrate: 这是一个经过清理和注释的版本,用于说明:

// 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
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM