2017-04-15 57 views
0

從tr開始引用時,如何獲取td中畫布的上下文?示例代碼:jquery,從tr獲取畫布上下文

<table> 
    <tr name='pool_row' id='swimming_pool'> 
     <td> 
     </td> 
     <td> 
     </td> 
     <td name='write_graphic'> 
      <canvas name='graphic' class='dataset_graphic' width='200' height='23'></canvas> 
     </td> 
     <td name='read_graphic'> 
      <canvas name='graphic' class='dataset_graphic' width='200' height='23'></canvas> 
     </td> 
    </tr> 
    <tr name='pool_row' id='hot_tub'> 
     <td> 
     </td> 
     <td> 
     </td> 
     <td name='write_graphic'> 
      <canvas name='graphic' class='dataset_graphic' width='200' height='23'></canvas> 
     </td> 
     <td name='read_graphic'> 
      <canvas name='graphic' class='dataset_graphic' width='200' height='23'></canvas> 
     </td> 
    </tr> 
</table> 
<script> 
    $("tr[name='pool_row']").each(function(){ 
     //Get Data for all pools from DB 
     //Loop over them, when match is found 
     //by id draw something. 
     var ctx = $(this).find("td[name='write_graphic']").find("canvas").getContext('2d'); 
    }); 
</script> 

顯然,真正的PHP生成的表我的工作是一個複雜得多。所有這些也都在setInterval函數中進行,因此它每隔1秒發生一次......但它不適用於該問題,只是它的重要性。

+0

取決於示例HTML的代表性。其他行的構造是否相同?如果不是,可能會有什麼變化? –

+0

有三種類型的行,pool_row是第一種類型......其他兩種類型將有不同的代碼,但行幾乎相同。只有pool_row類型會受到這個特定選擇器的影響。將會有多個池行,並且td的數量會隨着設計的進展而變化,所以我想按名稱來做......會讓jquery變得更小。所有游泳池行將被構造相同,並具有不同的值。 – gunslingor

回答

0

name屬性不應該用這樣的。

而是使用類,其目的是爲在同一個文檔內重複使用:

<table> 
    <tr class='pool_row' id='swimming_pool'> 
     <td> 
     </td> 
     <td> 
     </td> 
     <td class='write_graphic'> 
      <canvas class='dataset_graphic' width='200' height='23'></canvas> 
     </td> 
     <td class='read_graphic'> 
      <canvas class='dataset_graphic' width='200' height='23'></canvas> 
     </td> 
    </tr> 
    <tr class='pool_row' id='hot_tub'> 
     <td> 
     </td> 
     <td> 
     </td> 
     <td class='write_graphic'> 
      <canvas class='dataset_graphic' width='200' height='23'></canvas> 
     </td> 
     <td class='read_graphic'> 
      <canvas class='dataset_graphic' width='200' height='23'></canvas> 
     </td> 
    </tr> 
</table> 

現在您可以選擇畫布內容如下:

$("tr.pool_row canvas") // all pool_row canvases. 

$("tr.pool_row").eq(0).find("canvas") // both canvases in the first pool_row. 

$("tr.pool_row td.write_graphic canvas") // all pool_row write_graphic canvases. 

$("tr.pool_row td.read_graphic canvas") // all pool_row read_graphic canvases. 

這些只是例子。可以做更多的選擇。例如,如果有多於一個這種類型的表,您可能希望將選擇限制在其中一個表中,在這種情況下,事情會變得更加複雜,但並不顯着。

+0

名稱也被設計用於重複使用,但如果您堅持使用類別,則更改它不會影響css ...它的id字段旨在是唯一的。 – gunslingor

+0

你*可以*有重複的名字,但是與使用類相比,你會讓生活變得很難。 –

+0

除了在表單中,通常不會使用name屬性。 –