jquery 替换
jQuery 替换元素或内容的方法
使用 jQuery 替换元素或内容可以通过多种方式实现,以下是一些常见的方法:
替换元素内容
使用 .html() 方法可以替换元素的内部 HTML 内容:
$("#targetElement").html("<p>新内容</p>");
替换元素本身
使用 .replaceWith() 方法可以替换整个元素:
$("#oldElement").replaceWith("<div id='newElement'>新元素</div>");
替换文本内容
使用 .text() 方法可以替换元素的纯文本内容:
$("#targetElement").text("新的文本内容");
替换多个元素
使用 .each() 遍历并替换多个元素:
$(".items").each(function() {
$(this).replaceWith("<div class='new-item'>" + $(this).text() + "</div>");
});
使用回调函数替换
.replaceWith() 支持回调函数动态生成替换内容:

$(".dynamic-content").replaceWith(function() {
return "<div>" + $(this).data("new-content") + "</div>";
});
注意事项
- 替换操作会移除原有元素的事件处理程序和数据,需要重新绑定
- 使用
.detach()可以保留数据以便后续重新插入 - 大量 DOM 替换操作可能影响性能,建议批量处理
示例:替换表格行
$("tr.old-row").replaceWith(
"<tr class='new-row'><td>新数据1</td><td>新数据2</td></tr>"
);
以上方法可根据具体需求选择使用,jQuery 的替换操作提供了灵活的 DOM 更新方式。






