[英]How can I clone and change all ID's of a table with jQuery?
I want to clone a table
and change all its ID's adding a prefix. 我想克隆一个
table
并更改其所有ID,并添加一个前缀。
In the snippet below I change all tr
elements ID's adding the prefix my_
, using .find('tr').each(function()
. 在下面的代码段中,我使用
.find('tr').each(function()
更改所有tr
元素ID并添加前缀my_
。
With jQuery, how can I add a prefix name to all ID's of a table during the clone? 使用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/>
Search for all ID's and use attr(function)
which will in itself do an each
internally 搜索所有ID并使用
attr(function)
本身将在内部进行each
$newTable
.find('[id]')
.attr('id', function(_, id){
return 'new-prefix' + id;
})
You could search for every element that has the id
attr like this: 您可以搜索具有
id
attr的每个元素,如下所示:
$newTable
.find('[id]')
.each(function() {
$(this).attr('id', 'my_'+$(this).attr('id'));
});
That way, it will change the id of every element that has an id set. 这样,它将更改每个具有ID集的元素的ID。
Elements that don't have an ID set, wont be changed. 没有设置ID的元素将不会更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.