2017-06-19 20 views
2

テーブル行の内容にアクセスできません。 <tr>タグにアクセスすると、console.logにcontext: undefinedが表示されます。オブジェクトデザインパターンでjqueryでテーブル行の内容を取得する方法

マイコード:

<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)はトラブルになると思います。しかし、私はそれを変更する方法はありません。

+0

でなければなりません

var $row = $(this).parent(); 

hasan

答えて

0

これを試してみてください。

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(); 
+0

良いヒントだったこと!この代わりにtarget.eventを使用します。しかし、親を使用するには、最も近い( 'tr')を取った –

+0

私は最初に 'これは面白いようでした、これを見た問題を解決しようとしています:) –

0

問題はここにあると思われる、あなたは "このmyobj" と呼んでないとき

var $row = $(this).closest('tr'); 
関連する問題