我正在尝试使用下面的代码获取html表中所选行的行索引,但它不起作用。
$(function() {
$("#myTable tr").click(function() {
alert(this.rowIndex);
});
});
上述代码有什么问题?
答案 0 :(得分:2)
您的代码看起来很好,除非您没有像其他人那样添加jQuery引用 AND / OR 可能您的表是动态创建的,请尝试使用.on
作为event delegation
所以:
$(function() {
// use event delegation
$(document).on('click','#myTable tr', function() {
alert(this.rowIndex);
// or
alert($(this).index()); // jQuery way
});
});
答案 1 :(得分:0)
$('#table tr').each(function(indx, val) {
$(this).click(function() {
var index = $(this).index();
var value = $(this).text();
alert('This row index is ' + index + ' This row value is ' + value)
console.log(indx)
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id='table'>
<tr>
<td>qwe</td>
</tr>
<tr>
<td>123</td>
</tr>
<tr>
<td>123qwe</td>
</tr>
</table>
您可以使用.index()来获取tr的索引。
描述:从匹配的元素中搜索给定元素。
您也可以使用.each function
描述:迭代jQuery对象,为每个匹配的元素执行一个函数。
答案 2 :(得分:0)
同样的问题我几天前试着解决了。您可以将此代码用作类似问题的模板。我会评论这条路。
window.onload = function() {
/* variable stores html data as array for desired tag, this case it's 'tr' -*/
var test = this.test = $('tr');
/* loop traverses the row elements in the array, which element is clicked */
for (var i = 0; i < test.length; i++){
index = Array.prototype.indexOf.call(test,test[i]);
/* it's best to store the index inside the original row element which eases the access */
test[i].setAttribute('index',index);
/* on clicking the element it calls for a function which alerts the index */
test[i].onclick = alertTheClick ;
/* this is in case of debug */
console.log(index);
}
};
/* function definition */
function alertTheClick(index){ /* index value from loop */
alert(this.getAttribute('index')); /* index attribute from 'tr' element */
}