2012-06-30 76 views
0

我試圖通過jQuery在表上的td單元格上觸發單擊事件。我已經在不同的表中實現了行,沒有任何問題。作爲參考,該表格是一個montly日曆,點擊一個正方形將會提取當天的數據。jquery td單擊事件

我無法啓動該事件,因此我將代碼分解爲基本代碼並將其放在自己的頁面上,以確保沒有任何干擾。在CSS中的表類是table.calendar和這裏的代碼:

$('table.calendar').delegate('td','click',function() { 
     alert('Success'); 
     var href = $(this).find("a").attr("href"); 
     if (href) { 
      window.location = href; 
     } 
    }); 

我也試過它作爲.calendar沒有成功。我已經確認該課程在桌面上是正確的,並且沒有其他課程。我正在使用jquery 1.6

任何想法爲什麼事件沒有解僱?

+1

你確定你嘗試綁定事件之前的表被添加?你把你的代碼包裝在'$(document).ready(function ...'或'$(function ...'?什麼東西讓它等待dom加載? – andlrc

+0

@AndreasAL [delegate](http://api.jquery.com/delegate/)'將一個處理程序附加到與選擇器匹配的所有元素的一個或多個事件,**現在或將來**,基於特定的一組根元素「。 – Jashwant

+0

@Jashwant ya ?? ...但是,如果在綁定事件後添加了表格(根元素),我就開始討厭了。 – andlrc

回答

1

嘗試在準備回調包裝代碼:

jQuery(function($) { 
    $('table.calendar').delegate('td','click',function() { 
      alert('Success'); 
      var href = $(this).find("a").attr("href"); 
      if (href) { 
       window.location = href; 
      } 
     }); 
}); 

如果不到風度的工作出現了,你table.calender加入異步大posibility。然後嘗試:

$(document).deligate('table.calendar td', 'click', function() { 
    alert("Success!"); 
}); 

OR

$("table.calendar td").live('click', function() { 
    alert("Success!"); 
}); 

如果不到風度的工作你沒有任何表包含任何tdcalender

+0

沒有這些工作。我還修改了桌子上的班級,給它一個粉紅色的背景,以便我100%確定它正確地擊中了桌子。我認爲我沒有100%理解td點擊甚至是如何工作的? –

+0

@JonLeach如果你發佈一個例子和一些HTML我可以幫你。 – andlrc

0

這裏是原始代碼。請注意,我使用的是VS2010,因此有些代碼來自那裏。

<form method="post" action="WebForm1.aspx" id="form1"> 
//
<script type="text/javascript"> 



    jQuery(function ($) { 

     $('table.calendar').delegate('td', 'click', function() { 

      alert('Success'); 

      var href = $(this).find("a").attr("href"); 

      if (href) { 

       window.location = href; 

      } 

     }); 

    }); 

<div> 

<table id="tblCalendar" class="calendar" rules="all" border="1" style="width:70%;float:right;border-width:2px;border-color:Gray"> 

<tr style="border-width:2px;border-style:solid;"> 

    <th><a id="LinkBack" href="javascript:__doPostBack(&#39;LinkBack&#39;,&#39;&#39;)" style="font-size:Large;"><<</a></th><th align="center" colspan="1"><span id="CalendarTitle" style="font-size:Large;"></span></th><th align="center"><a id="LinkForward" href="javascript:__doPostBack(&#39;LinkForward&#39;,&#39;&#39;)" style="font-size:Large;">>></a></th> 

</tr><tr> 

    <td class="Regular">3</td><td>4</td><td>5</td> 

</tr> 

</div> 

</form> 

+0

注意我也嘗試過使用.Regular類 –