gpt4 book ai didi

jquery - 为什么移除后阶梯会消失?

转载 作者:太空宇宙 更新时间:2023-11-03 21:09:38 25 4
gpt4 key购买 nike

我遇到了这个问题,当点击 tr 时,id 被重新排序但是 td 样式消失了,我不知道为什么。

$("tr").on("click", function() {
var parent = $(this).parent();
$(this).remove();
parent.children("tr").each(function(i){
$(this).attr('id', (i+1));
$(this).html((i+1));
});
});
tr{
color: #444;
background: #ccc;
}
td{
min-width: 125px;
padding: 10px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr id="1">
<td>1</td>
</tr>
<tr id="2">
<td>2</td>
</tr>
<tr id="3">
<td>3</td>
</tr>
<tr id="4">
<td>4</td>
</tr>
</table>

最佳答案

您正在用对 .html 的调用替换 tr 的内容,清除其中的 td。您可能打算替换 td 的内容:

$("tr").on("click", function() {
var parent = $(this).parent();
$(this).remove();
parent.children("tr").each(function(i){
$(this).attr('id', (i+1));
$(this).find("td").html((i+1));
// ^^^^^^^^^^^
});
});

更新的代码段:

$("tr").on("click", function() {
var parent = $(this).parent();
$(this).remove();
parent.children("tr").each(function(i){
$(this).attr('id', (i+1));
$(this).find("td").html((i+1));
// ^^^^^^^^^^^
});
});
tr{
color: #444;
background: #ccc;
}
td{
min-width: 125px;
padding: 10px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr id="1">
<td>1</td>
</tr>
<tr id="2">
<td>2</td>
</tr>
<tr id="3">
<td>3</td>
</tr>
<tr id="4">
<td>4</td>
</tr>
</table>

旁注:其他一些想法:

  • 您可以使用 siblings 而不是 parent.children():
  • $(this).attr("id", i+1) 是很长的写法this.id = i+1。 :-)
  • 无需重复i+1

所以:

$("tr").on("click", function() {
var siblings = $(this).siblings();
$(this).remove();
siblings.each(function(i){
++i;
this.id = i;
$(this).find("td").html(i);
});
});

$("tr").on("click", function() {
var siblings = $(this).siblings();
$(this).remove();
siblings.each(function(i){
++i;
this.id = i;
$(this).find("td").html(i);
});
});
tr{
color: #444;
background: #ccc;
}
td{
min-width: 125px;
padding: 10px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr id="1">
<td>1</td>
</tr>
<tr id="2">
<td>2</td>
</tr>
<tr id="3">
<td>3</td>
</tr>
<tr id="4">
<td>4</td>
</tr>
</table>

关于jquery - 为什么移除后阶梯会消失?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48326494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com