如何在jquery中查找表下一个单元格

时间:2015-04-21 18:26:02

标签: jquery html asp.net

连续有两个单元格,第一个单元格有表格,下一个单元格有按钮。如何在下一个单元格中找到按钮。

每行最后一个单元格中的所有按钮都具有相同的id,因此我需要找到当前行中的最后一个单元格或当前单元格旁边的单元格。

如果勾选了当前单元格中的任何复选框,我正在尝试启用按钮。

<table>
        <tr>
            <td>
                <table>
                    <tr>
                        <td><input id="Checkbox1" type="checkbox" /></td>
                        <td><input id="Checkbox2" type="checkbox" /></td>
                    </tr>
                </table> 
            </td>
            <td><input id="Button1" type="button" value="button" /></td>
        </tr>

        <tr>
            <td>
                <table>
                    <tr>
                        <td><input id="Checkbox1" type="checkbox" /></td>
                        <td><input id="Checkbox2" type="checkbox" /></td>
                    </tr>
                </table> 
            </td>
            <td><input id="Button1" type="button" value="button" /></td>
        </tr>
    </table>

1 个答案:

答案 0 :(得分:0)

首先,ID必须在文档中是唯一的,否则文档无效。如果将ID选择器传递给jQuery或仅使用document.getElementById()函数,则选择第一个匹配元素。

要获取input[type=button]元素,您可以遍历复选框的祖先,并使用td方法选择包装.closest(),然后使用{选择下一个单元格的后代按钮{1}}和.next()方法:

.find()

上面的代码段使用$('input[type=checkbox]').on('change', function() { var button = $(this.parentNode.parentNode) .closest('td') .next() .find('input[type=button]'); }); 来选择复选框的this.parentNode.parentNode祖父。原因是,jQuery tr方法从测试当前元素开始。 closest会返回$(this).closest('td')个父级,td会返回当前的$(this.parentNode)个。