Jquery,从tr

时间:2017-04-15 01:39:52

标签: javascript jquery canvas find closest

从tr开始引用时如何获取td中画布的上下文?示例代码:

<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秒发生一次......但它不适用于问题,只是它的重要性。

2 个答案:

答案 0 :(得分:0)

感谢这篇文章,我经常在处理更复杂的问题时忘记这一点:jQuery equivalent of getting the context of a Canvas

var ctx = $(this).find("td[name='write_graphic'] ").find("canvas")[0].getContext('2d');

答案 1 :(得分: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.

这些只是一些例子。可以做出更多选择。例如,如果有多个此类型的表,您可能希望将选择约束到其中一个表,在这种情况下,事情会变得更复杂,但不会显着。