2017-06-19 46 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

當你叫 「MyObj中」 – 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

這個問題似乎在這裏,

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

var $row = $(this).closest('tr');