Fiddle Example

该表的类名称如下:

dsdds_imagedfdd_imagesdadsa_titledsdf_title3434_description48fd_description

它们只是下划线之前的随机字符串。您如何将所有这些随机字符串替换为jQuery中的“占位符”一词,以使它们成为placeholder_titleplaceholder_imageplaceholder_description

HTML:

<button id="cleartable">Clear</button>
<table class="toptable">
  <tr>
    <th class="dsdds_image">1</th>
    <th class="r3dde_image">2</th>
    <th class="s43434_image">3</th>
  </tr>
  <tr>
    <td class="44665_description">4</td>
    <td class="3434d_description">5</td>
    <td class="a34df_description">6</td>
  </tr>
  <tr>
    <td class="dfs4rf_title">7</td>
    <td class="adf43df_title">8</td>
    <td class="dsffds4_title">9</td>
  </tr>
</table>


我失败的尝试

$("#cleartable").click(function() {
  $(".toptable td,.toptable th").each(function() {
    var changeclass = $(this).attr("class");
    changeclass.replace(/^[^_]+/,"placeholder");
  });
});

最佳答案

您可以简单地做到这一点:

$("#cleartable").click(function() {
   $(".toptable td,.toptable th").each(function() {
     var changeclass = $(this).attr("class");
     $(this).attr('class',changeclass.replace(/^[^_]+/,"placeholder"));//See this?
   });
});


.replace为您提供一个新字符串,并且不会更改原始字符串。因此,您需要在某个地方重新分配它。

09-15 20:00