我无法访问表格行内容。访问context: undefined标记时,我在console.log中得到一个<tr>

我的代码:

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Color</th>
      <th>Size</th>
      <th>Position</th>
      <th>Print</th>
      <th>Delete</th>
    </tr>
  </thead>
  <tbody id="result">
    <tr>
      <td>myName</td>
      <td>myColor</td>
      <td>mySize</td>
      <td>myPosition</td>
      <td><button name="print" type="button">print</button></td>
      <td><button name="delete" type="button">delete</button></td>
    </tr>
  </tbody>
</table>


我的剧本

var myObj = {
    $res:null,
    init: function() {
      this.cacheDom();
      this.bindEvents();
    },
    cacheDom: function() {
      $res = $('#result');
    },
    bindEvents: function() {
      $res.on('click', 'button[name=print]', this.sendData.bind(this));
    },
    sendData: function() {
      var $row = $(this).parent();
      var $myName = $row.find('td:eq(0)').text();
      console.log($row);
      console.log($myName);
    }
  };
  myObj.init();


我认为$(this)会带来麻烦。但是我不怎么改变它。

最佳答案

尝试这个 :

    var myObj = {
        $res:null,
        init: function() {
          this.cacheDom();
          this.bindEvents();
        },
        cacheDom: function() {
          $res = $('#result');
        },
        bindEvents: function() {
          $res.on('click', 'button[name=print]', this.sendData.bind(this));
        },
        sendData: function(event) {
          var $row = $(event.target).closest('tr');
          var $myName = $row.find('td:eq(0)').text();
          console.log($row);
          console.log($myName);
        }
      };
      myObj.init();

10-06 03:59