javascript - 不要从表 td 第一个子元素中删除内容

标签 javascript jquery html css-selectors

( 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? 
   }   

   });
});

最佳答案

尝试

Fiddle demo

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('') .

.index()

.filter()

.is()

关于javascript - 不要从表 td 第一个子元素中删除内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23853668/

相关文章:

javascript - 将 javascript 放在一个 .js 文件中还是将其分解为多个 .js 文件?

Javascript:是否可以将新函数注入(inject)到基础 'class/object' 中,该函数将在所有子 -'classes/objects' 中可用?

javascript - 在 javascript 中的文本框 textchange 事件上选中=True

javascript - JQuery 和 Javascript : Writing Better code - How can I improve on both

jQueryUI 可排序允许滚动并为移动设备添加延迟

javascript - 第二次单击后,单选按钮值在 IE 中不正确。在其他浏览器中工作

javascript - 如何在多个命名空间中命名函数?

javascript - 如何从offcanvas打开offcanvas

html - 制作一个始终保持其比例的网站

html - 如何删除媒体查询中的某些 html?(在 iphone 上不会存在)