最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get row data failed, error of Cannot create property 'guid' on string - Stack Overflow

programmeradmin0浏览0评论

I'm using jquery datatables. I got error of Cannot create property 'guid' on string when I tried to retrieve the row data.

var employersTable = $('#employersTable').DataTable();

$('#add').click(function() {
  addRow($('.username').val(), $('.phone').val());
});

$('body').on('click', '#employersTable tr', retrieveRow(this));

function addRow(username, phone) {
  employersTable.row.add([
    '<td>' + username + '</td>',
    '<td>' + phone + '</td>',
  ]).draw();
}

function retrieveRow(e) {
  alert('fire')
  tr = e.target;

  row = employersTable.row(tr);

  detail_data = row.data();
  $("#result").empty().html(detail_data[0] + " " + detail_data[1])
}

One more strange thing is my function retrieveRow fire on init, why? I put the function within a click event.

I'm using jquery datatables. I got error of Cannot create property 'guid' on string when I tried to retrieve the row data.

http://jsfiddle.net/rqx14xep

var employersTable = $('#employersTable').DataTable();

$('#add').click(function() {
  addRow($('.username').val(), $('.phone').val());
});

$('body').on('click', '#employersTable tr', retrieveRow(this));

function addRow(username, phone) {
  employersTable.row.add([
    '<td>' + username + '</td>',
    '<td>' + phone + '</td>',
  ]).draw();
}

function retrieveRow(e) {
  alert('fire')
  tr = e.target;

  row = employersTable.row(tr);

  detail_data = row.data();
  $("#result").empty().html(detail_data[0] + " " + detail_data[1])
}

One more strange thing is my function retrieveRow fire on init, why? I put the function within a click event.

Share Improve this question edited Dec 12, 2019 at 17:40 davidkonrad 85.5k17 gold badges209 silver badges271 bronze badges asked Jun 18, 2016 at 4:29 Alicia BrandonAlicia Brandon 5752 gold badges6 silver badges13 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 15

Your main problem is this line :

$('body').on('click', '#employersTable tr', retrieveRow(this));
                                            ^^^^^^^^^^^^^^^^^

This actually executes retrieveRow() right away. When you reference to a function variable in a on() event handler, reference to it as it was a variable :

$('body').on('click', '#employersTable tr', retrieveRow);

You have a different problem in retrieveRow() :

tr = e.target;

e.target is not necessarily a <tr>, it is most likely the <td> you clicked on. The event handler is targeting #employersTable tr so this contain the reference to the <tr> :

tr = $(this)

is the correct, more safe is

tr = $(e.target).closest('tr')

forked fiddle -> http://jsfiddle.net/nkaq816f/

发布评论

评论列表(0)

  1. 暂无评论