javascript - 如何使用 jQuery 克隆和更改表的所有 ID?

标签 javascript jquery

我想克隆一个并更改其所有 ID 添加前缀。

在下面的代码片段中,我使用 .find('tr').each(function().

使用 jQuery,如何在克隆期间为表的所有 ID 添加前缀名称?

var $newTable = $('table.copyable:first').clone();
$newTable.removeClass('copyable');
$newTable
  .find('tr')
  .each(function() {
    $(this).attr('id', 'my_'+$(this).attr('id'));
  });

$('#list-player-songs').html('');
$newTable.appendTo($('#list-player-songs'));
table.copyable {
  background: antiquewhite;
}
table td {
  border:1px solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h3>Original table</h3>
<table class="copyable">
  <tbody class="sortable">
    <tr id="track251">							
      <td><div data-track-name="love.mp3" id="play251"></div></td>
        <td id="song-url251">love</td>
    </tr>
    <tr id="track241">							
      <td><div data-track-name="hate.mp3" id="play241"></div></td>
        <td id="song-url241">hate</td>
    </tr>
    <tr id="track233">							
      <td><div data-track-name="think.mp3" id="play233"></div></td>
        <td id="song-url233">think</td>
    </tr>
  </tbody>
</table>

<h3>Copied elements</h3>
<div id="list-player-songs"></div>

<hr/>
<br/><br/><br/>

最佳答案

搜索所有 ID 并使用 attr(function) 这本身将在内部执行 each

$newTable
    .find('[id]')
    .attr('id', function(_, id){
       return 'new-prefix' + id;
    })

关于javascript - 如何使用 jQuery 克隆和更改表的所有 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41430378/

相关文章:

javascript - div 中的最后一个 span 改变了它的宽度

javascript - 通过ajax将关联PHP数组传递给javascript时保留其顺序

javascript - 检查元素的文本是否与另一个元素的文本相同

javascript - jQuery 函数 - 设置字符串参数

javascript - 从特定类别中删除最后一个单词

c# - 在 jquery 中单击后绑定(bind) css 样式?

JavaScript 通过在不损失高度的情况下滑动更多内容来替换内容

javascript - ionic + Genymotion : JavaScript logs

javascript - 在 CSS 动画之后滚动到 anchor ?

javascript - 更改按钮的功能