var stop_index = 1;
$('.add_stop').click(function(){
tr = '#stop' + stop_index
$(tr).after('<tr id="stop'+ stop_index + '"><td>'+ stop_index +'</td></tr>');
stop_index ++;
});
这是代码(在表格中添加一行)。
但是,它不起作用。
如果我编写这样的代码,它就可以工作。
$('#stop1').after('<tr id="stop'+ stop_index + '"><td>'+ stop_index +'</td></tr>');
问题是什么?
最佳答案
查看您的代码,您已经需要 <tr id="stop1">
元素使其工作,然后下一个也添加 id stop1
。也许您应该尽早增加该值
var stop_index = 1;
$('.add_stop').click(function(){
tr = '#stop' + stop_index
stop_index ++;
$(tr).after('<tr id="stop'+ stop_index + '"><td>'+ stop_index +'</td></tr>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr id="stop1"><td>1</td></tr>
</table>
<button class="add_stop">
Add
</button>
虽然增加 id 有点反模式,但您应该考虑是否需要它们。如果您只是尝试添加行,则添加到现有列表的末尾要简单得多
var index = 1;
$('.add_stop').click(function(){
$('table').append('<tr><td>'+ ++index +'</td></tr>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr><td>1</td></tr>
</table>
<button class="add_stop">
Add
</button>
关于javascript - jquery 使用 .after() 在表中添加行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50638372/