2015-07-21 42 views
0

我想用jQuery獲取表中某行的值,當用戶點擊它時。如何使用jQuery選擇表中某一行的值?

我曾嘗試這種解決方案,但它不能正常工作:

$(document).ready(function() { 
 

 

 
       $.post("./php/myjson.php", function(data, status) { 
 
        obj = JSON.parse(data); 
 
        var trHTML = ''; 
 
        for (var i = 0; i < obj.giocatori.length; i++) { 
 

 
         trHTML += '<tr><td><img src="../media/image/squadre/' + obj.giocatori[i].Squadra.toLowerCase() + '.png"/></td><td>'+obj.giocatori[i].Giocatore+'</td><td>' + obj.giocatori[i].Cognome + '</td><td>' + obj.giocatori[i].Prezzo + '</td></tr>'; 
 
        } 
 
        trHTML+='</tbody>'; 
 
        $('#records_table').append(trHTML); 
 

 
       }); 
 
       $("#records_table tr").on("click", function() { 
 
         alert($(this).find('td:nth-child(2)').html()); 
 
       }); 
 

 
      });
table tbody tr:hover { 
 
    background-color: orange; 
 
    cursor: pointer; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table id="records_table" border="1"> 
 

 
     <tbody> 
 
      <tr> 
 
       <th>Squadra</th> 
 
       <th>ID</th> 
 
       <th>Cognome</th> 
 
       <th>Prezzo</th> 
 

 
      </tr> 
 

 
    </table>

哪裏錯誤?

+3

改變這個$(「#records_table tr」).on(「click」,function(){'to'$(「#records_table」).on(「click」,'tr',function(){' –

+0

它的工作原理!爲什麼我的代碼不正確? –

+0

@Alexander讓它成爲一個答案.... – epascarello

回答

1

即使表格在頁面加載時存在,其內容在頁面加載後(在事件DOM ready之後)加載。你想使用委託事件。因此,試試這個:

$("#records_table").on("click", "tr", function() { 
    alert($('td', this).eq(2).html()); 
}); 

注意:添加此節 - 你的版本 - 在成功回叫Ajax調用新的內容被添加也應該工作後。

1

您在HTML中保留tbody,但將內容添加到表中。請更改以下內容。

$(文件)。就緒(函數(){

  $.post("./php/myjson.php", function(data, status) { 
       obj = JSON.parse(data); 
       var trHTML = ''; 
       for (var i = 0; i < obj.giocatori.length; i++) { 

        trHTML += '<tr><td><img src="../media/image/squadre/' + obj.giocatori[i].Squadra.toLowerCase() + '.png"/></td><td>'+obj.giocatori[i].Giocatore+'</td><td>' + obj.giocatori[i].Cognome + '</td><td>' + obj.giocatori[i].Prezzo + '</td></tr>'; 
       } 
       $('#records_table tbody').append(trHTML); 

      }); 
      $("#records_table tr").on("click", function() { 
        alert($(this).find('td:nth-child(2)').html()); 
      }); 

     }); 

,以及你可以在HTML關閉TBODY。

Squadra ID Cognome 來自Prezzo
相關問題