【问题标题】:Don't remove content from table td first child不要从表 td first child 中删除内容
【发布时间】:2014-05-25 17:25:27
【问题描述】:

(JSfiddle Example)

我想排除删除 td first child 中的文本,以便保留文本 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? 
   }   

   });
});

【问题讨论】:

    标签: javascript jquery html css-selectors


    【解决方案1】:

    试试

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

    【讨论】:

      【解决方案2】:

      也许是一个简单的方法:

      var clear = $(".toptable td+td,.toptable th")
      

      【讨论】:

        【解决方案3】:

        在您使用的代码中

        if (clear.not(':first-child'))
        

        jQuery 的 .not() 将返回一个 jQuery 实例而不是布尔值,所以这可能不是你所期望的。

        做你想做的事的快速简单的方法是

        clear.not(':first-child').text('');
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-06-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-14
          相关资源
          最近更新 更多