鑑於錶行的一些單擊事件確定目標TD:當TR被點擊
$("tr.somerow").click(function(){
//do some stuff
//can I determine the TD under the cursor at the time of clicking?
})
我可以確定哪些TD(或子元素)是將光標定位在點擊的時候下?
鑑於錶行的一些單擊事件確定目標TD:當TR被點擊
$("tr.somerow").click(function(){
//do some stuff
//can I determine the TD under the cursor at the time of clicking?
})
我可以確定哪些TD(或子元素)是將光標定位在點擊的時候下?
$("tr.somerow").click(function(e){
var target = $(e.target); // sets to the td or the element that was clicked
//do some stuff
})
要查找點擊<td>
無論任何子元素,使用var target = $(e.target).closest("td");
代替。
如果您可以更改腳本,那麼可以利用jquerys .delegate函數。這樣可以避免發生多重綁定點擊事件,並且在事件處理程序中,此上下文將是單擊的td元素的上下文。
$('tr.somerow').delegate('td', 'click', function(){
//this refers to the td
})
這是最好的解決方案,唯一需要注意的是開發人員需要知道的代表將綁定到任何未來的'tr.somerow '被創造出來。 –
@大衛它不會。你現場混淆了它。 – shesek
@shesek 「.delegate(selector,eventType,handler)返回:jQuery 描述:基於一組特定的根元素,爲現在或未來與選擇器匹配的所有元素附加一個處理程序到一個或多個事件「。 「現在或將來」 - 委託與現場一樣,但它也處理rebinding'this',並且在事件傳播中被稍早調用。 http://api.jquery.com/delegate/ –
幾個主要是正確的答案,但一個錯過最接近的,另一個做了很多不必要的錯誤處理。
$("tr.selector").click(function(e){
var td = $(e.target).closest('td');
});
將點擊事件放在TD上並從中確定TR會更容易。 – RoToRa
@RoToRa - 我的確想到了這一點,但我不確定是否有數十個細胞與幾十個細胞相比。您還必須與填充競爭,單元格之間的間隙是否會產生點擊。 –