获取动态创建的单击行的索引
Getting index of clicked row that's dynamically created
我创建了一个 table 三行,可以使用添加按钮展开。我想知道我点击的每一行的索引。我有一段代码在三个自动生成的行上工作得很好,但在我使用添加按钮添加的行上却没有。
这里有一个 fiddle 基本上显示了我的问题:http://jsfiddle.net/4wa5kfpz/,我的实际代码中有更多的东西所以这是一个 basic/stripped 版本。
如您所见,在前两行和最后两行之间添加的行在单击时没有响应。我试过类似的方法(见下文,基于 this question)将点击事件添加到 table 行,但这没有用。
$("table tr").on('click', '#myTable tr', function(e){
alert('Clicked row '+ ($(this).index()+1) );
});
有什么想法吗?
使用.on
事件:
$("#myTable").on('click', 'tr', function(){
alert('Clicked row '+ ($(this).index()+1) );
});
你可以这样做:
<html>
<head>
<title>Row indexes</title>
<script type="text/javascript">
onload = function() {
if (!document.getElementsByTagName || !document.createTextNode) return;
var rows = document.getElementById('my_table').getElementsByTagName('tbody')[0].getElementsByTagName('tr');
for (i = 0; i < rows.length; i++) {
rows[i].onclick = function() {
alert(this.rowIndex + 1);
}
}
}
</script>
</head>
<body>
<table id="my_table">
<tbody>
<tr><td>first row</td></tr>
<tr><td>second row</td></tr>
</tbody>
</table>
</body>
</html>
或者你可以这样做:
$('#thetable').find('tr').click( function(){
alert('You clicked row '+ ($(this).index()+1) );
});
希望对您有所帮助!!!
我创建了一个 table 三行,可以使用添加按钮展开。我想知道我点击的每一行的索引。我有一段代码在三个自动生成的行上工作得很好,但在我使用添加按钮添加的行上却没有。
这里有一个 fiddle 基本上显示了我的问题:http://jsfiddle.net/4wa5kfpz/,我的实际代码中有更多的东西所以这是一个 basic/stripped 版本。
如您所见,在前两行和最后两行之间添加的行在单击时没有响应。我试过类似的方法(见下文,基于 this question)将点击事件添加到 table 行,但这没有用。
$("table tr").on('click', '#myTable tr', function(e){
alert('Clicked row '+ ($(this).index()+1) );
});
有什么想法吗?
使用.on
事件:
$("#myTable").on('click', 'tr', function(){
alert('Clicked row '+ ($(this).index()+1) );
});
你可以这样做:
<html>
<head>
<title>Row indexes</title>
<script type="text/javascript">
onload = function() {
if (!document.getElementsByTagName || !document.createTextNode) return;
var rows = document.getElementById('my_table').getElementsByTagName('tbody')[0].getElementsByTagName('tr');
for (i = 0; i < rows.length; i++) {
rows[i].onclick = function() {
alert(this.rowIndex + 1);
}
}
}
</script>
</head>
<body>
<table id="my_table">
<tbody>
<tr><td>first row</td></tr>
<tr><td>second row</td></tr>
</tbody>
</table>
</body>
</html>
或者你可以这样做:
$('#thetable').find('tr').click( function(){
alert('You clicked row '+ ($(this).index()+1) );
});
希望对您有所帮助!!!