![](/img/trans.png)
[英]Get html table row and cell index with javascript function
[英]Get index of a table cell relative to the row
我在表格的單元格中有一些checkbox
。 我要在每個事件上綁定一個click事件。 單擊時,我想獲取當前單元格相對於父行的索引。
例如:
<tr>
<td>...</td>
<td><input type='checkbox'>....</td>
</tr>
我想為該checkbox
click事件獲取1
。
這是我正在使用的JavaScript代碼:
Grid.tbody.find("input[type='checkbox']").each(function () {
$(this).click(function () {
var isChecked = $(this).prop('checked');
var dataItem = tablesGrid.dataItem($(this).closest('tr'));
var i = $(this).index();
alert(i);
});
});
在此JavaScript代碼中,我想獲取當前單元格的索引,即I
變量,該變量不起作用。
$(this)
$(this).index()
$(this)
中的$(this).index()
是指復選框,而不是單元格td
。
要獲取單元格索引使用,
$(this).closest('td').index(); //or $(this).parent().index() if there is no further nesting.
Grid.tbody.find("input[type='checkbox']").each(function () {
$(this).click(function () {
var isChecked = $(this).prop('checked');
var dataItem = tablesGrid.dataItem($(this).closest('tr'));
var i = $(this).closest('td').index();
alert(i);
});
});
另外,我建議您使用.change()
事件代替click()
要獲取可見元素索引,
var $currentTr = $(this).closest('tr');
var i = $('td:visible',$currentTr).index($(this).closest('td'))
您可以調用td
的索引, $(this).index()
將為您提供其父代( td
)中checkbox
的索引
Grid.tbody.find("input[type='checkbox']").click(function () {
var isChecked = this.checked;
var dataItem = tablesGrid.dataItem($(this).closest('tr'));
var i = $(this).closest('td').index();
alert(i);
});
您可以使用目標復選框上的parent()調用來訪問列的索引。 如果這是您的桌子的樣子。
$("#grid input[type='checkbox']").click(function(e) { var isChecked = $(this).prop('checked'); var $dataItem = $(this).parent(); var i = $dataItem.index(); // Gives the column number in any row $('#log').append("<p>").text(i); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="log"></div> <table id="grid"> <tr> <td>Row 1</td> <td> <input type="checkbox" name="check1"> </td> <td> <input type="checkbox" name="check1"> </td> <td> <input type="checkbox" name="check1"> </td> <td> <input type="checkbox" name="check1"> </td> </tr> <tr> <tr> <td>Row 2</td> <td> <input type="checkbox" name="check2"> </td> <td> <input type="checkbox" name="check2"> </td> <td> <input type="checkbox" name="check2"> </td> <td> <input type="checkbox" name="check2"> </td> </tr> <tr> <tr> <td>Row 3</td> <td> <input type="checkbox" name="check3"> </td> <td> <input type="checkbox" name="check3"> </td> <td> <input type="checkbox" name="check3"> </td> <td> <input type="checkbox" name="check3"> </td> </tr> </table>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.