2011-12-16 58 views
0

的TD我有一個像下面查找到相關的表onclick事件

<table onclick="dosomething()"> 
<tr><td>11</td><td>12</td><td>13</td></tr> 
<tr><td>11</td><td>12</td><td>13</td></tr> 
<tr><td>11</td><td>12</td><td>13</td></tr> 
</table> 

後,我點擊表的表,我需要找到在其上點擊發生的TD。我不能在tr或td上寫上onclick事件。

+1

我認爲事件只註冊爲從表中發起。 – 2011-12-16 13:29:27

+1

您可以使用`event.target`,但不應該使用內聯處理程序。 – pimvdb 2011-12-16 13:30:16

回答

0
$(function(){ 
    $("#tbl").bind("click", function(e){ 
     if(e.target.tagName == "TD"){ 
      //do your magic 
     } 
    }); 
}); 
1

你可以做這樣的事情(給你table一類myClass - 或任何你想要的):

function tableClicked(td) { 
    // Do something dependent on the td which was clicked 
} 

$(document).ready(function() { 
    $("table.myClass td").click(function() { 
     tableClicked(this); 
    }); 
}); 

這意味着你不必onclick屬性添加到<td>標籤。

+0

嗯,他仍然在添加它們......(只是沒有手動添加標記!) – 2011-12-16 13:33:40

0

我會傾倒的onclick併爲此

$("#myTable td").click(function() { 
    $(this).html(); // get the value 
    $(this).hide(); // hide it 
    $(this).remove(); // remove it 
}); 

<table id="myTable"> 
    <tr><td>11</td><td>12</td><td>13</td></tr> 
    <tr><td>11</td><td>12</td><td>13</td></tr> 
    <tr><td>11</td><td>12</td><td>13</td></tr> 
</table> 
1

的ID添加到表和刪除的onClick處理程序。這是爲了分離行爲和內容。

<table id="tableId"> 

因爲事件會冒泡,捕捉到它的表體上,找到目標,所以你不需要事件偵聽器添加到每個TD。

$('#tableId').click(function(e){ 
    //the td is the target where event happens 
    var td=e.target; 
});