Javascript 是否有其他方法可以多次更换特定元件?
如果我想用如下id多次替换元素:Javascript 是否有其他方法可以多次更换特定元件?,javascript,jquery,Javascript,Jquery,如果我想用如下id多次替换元素: $("#anIdElement").replacewith("#anotherIdElement"); 这不应该起作用,所以我的问题是:什么可以用来多次用另一个元素替换一个特定元素 例如: <table> <tr> <td id="theFirsttd">Original content</td> </tr> <tr> <td
$("#anIdElement").replacewith("#anotherIdElement");
这不应该起作用,所以我的问题是:什么可以用来多次用另一个元素替换一个特定元素
例如:
<table>
<tr>
<td id="theFirsttd">Original content</td>
</tr>
<tr>
<td id="atd">Replace the current content by the original</td>
</tr>
<tr>
<td id="atd">Replace the current content by the original</td>
</tr>
</table>
原始内容
将当前内容替换为原始内容
将当前内容替换为原始内容
这里的问题是我不能用名为atd的id替换元素,我只能替换一次。我说得对吗?
那么,是否可以使用类似于
remove()
然后append()
的方法来获得它?您可以将所有想要更改的id放入数组中并循环到它上
var数组=['theFirsttd','atd']
for(数组的变量项){
$(`${item}`)attr(“id”,“newId”);
}
请注意,在几个元素上是否有相同的id名称(这是不应该发生的,因为id应该是唯一的)
希望它能有所帮助。首先,您认为HTML无效,因为两个对象共享相同的id-这可以通过创建这些类来解决。其次,假设您只是使用jQuery将一个对象的内容复制到另一个对象,您可以执行以下操作:
$('.atd').html($('theFirsttd').html());
在jQuery中,您可以使用这些代码,但首先必须修复示例中的html:
<table>
<tr>
<td id="theFirsttd">Original content</td>
</tr>
<tr>
<td class="atd">Replace the current content by the original</td>
</tr>
<tr>
<td class="atd">Replace the current content by the original</td>
</tr>
</table>
<script>
// reemplace all the items (jQuery)
$(function(){ // <- wait for the DOM
var $first = $('#theFirsttd');
$('.atd').each(function{ // <- eval each element with atd class selector
$(this).replaceWith($first.clone()) // <- replace each one with first td clone
});
});
</script>
原始内容
将当前内容替换为原始内容
将当前内容替换为原始内容
//重新嵌入所有项(jQuery)
$(function(){//问题不存在,因为id必须是唯一的,因此始终只有一个元素具有特定id;)是的,我尝试克隆,但它没有给我相同的id,并且单元格是使用id生成的。请考虑使用document.getElementByClassNames()
,它将把div存储在一个数组中。在源代码处(即生成HTML的地方)修复它。在JS中修复这个问题的任何尝试都是一种黑客行为,而不是解决底层问题。非常感谢您的帮助!