( JSfiddle Example )
我想排除删除 td 第一个子项中的文本,以便保留文本 Sale
,Age
,例如:
原始 HTML:
<table class="toptable"><thead>
<tr>
<th class="dsdds_image">-</th>
<th class="r3dde_image">-</th>
<th class="s43434_image">-</th>
</tr></thead><tbody>
<tr>
<td class="44665_description">Name</td>
<td class="3434d_description">Alan</td>
<td class="a34df_description">John</td>
</tr>
<tr>
<td class="dfs4rf_title">Age</td>
<td class="adf43df_title">8</td>
<td class="dsffds4_title">9</td>
</tr></tbody>
</table>
在remove()
之后,应该是
<table class="toptable"><thead>
<tr>
<th class="dsdds_image"></th>
<th class="r3dde_image"></th>
<th class="s43434_image"></th>
</tr></thead><tbody>
<tr>
<td class="44665_description">Name</td>
<td class="3434d_description"></td>
<td class="a34df_description"></td>
</tr>
<tr>
<td class="dfs4rf_title">Age</td>
<td class="adf43df_title"></td>
<td class="dsffds4_title"></td>
</tr></tbody>
</table>
我在删除函数之前使用 if 语句检查它是否为 :first-child
但它仍然清除第一个子文本。谁能给我一些建议吗?
$('#cleartable').on('click', function () {
var clear = $(".toptable td,.toptable th")
if (clear.not(':first-child')){ //*******This part
clear.contents().filter(function(){
return this
}).remove();
}
clear.each(function() {
var $this = $(this)
if ($this.attr('class')){
var changeclass = $(this).attr("class");
$this.attr('class',changeclass.replace(/^[^_]+/,"placeholder"));//See this?
}
});
});
最佳答案
尝试
clear.filter(function () {
return $(this).index() !== 0; //return false for the first indexed element inside the parent
//return !$(this).is(':first-child'); you can also use
}).remove(); //if you don't wanna remove them set empty text .text('') .
关于javascript - 不要从表 td 第一个子元素中删除内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23853668/