- jQuery 教程
- jQuery - 首页
- jQuery - 路线图
- jQuery - 概述
- jQuery - 基础
- jQuery - 语法
- jQuery - 选择器
- jQuery - 事件
- jQuery - 属性
- jQuery - AJAX
- jQuery DOM 操作
- jQuery - DOM
- jQuery - 添加元素
- jQuery - 删除元素
- jQuery - 替换元素
- jQuery CSS 操作
- jQuery - CSS 类
- jQuery - 尺寸
- jQuery - CSS 属性
- jQuery 效果
- jQuery - 效果
- jQuery - 动画
- jQuery - 链式操作
- jQuery - 回调函数
- jQuery 遍历
- jQuery - 遍历
- jQuery - 遍历祖先元素
- jQuery - 遍历子孙元素
- jQuery UI
- jQuery - 交互
- jQuery - 小部件
- jQuery - 主题
- jQuery 参考
- jQuery - 选择器
- jQuery - 事件
- jQuery - 效果
- jQuery - HTML/CSS
- jQuery - 遍历
- jQuery - 杂项
- jQuery - 属性
- jQuery - 实用工具
- jQuery 插件
- jQuery - 插件
- jQuery - PagePiling.js
- jQuery - Flickerplate.js
- jQuery - Multiscroll.js
- jQuery - Slidebar.js
- jQuery - Rowgrid.js
- jQuery - Alertify.js
- jQuery - Progressbar.js
- jQuery - Slideshow.js
- jQuery - Drawsvg.js
- jQuery - Tagsort.js
- jQuery - LogosDistort.js
- jQuery - Filer.js
- jQuery - Whatsnearby.js
- jQuery - Checkout.js
- jQuery - Blockrain.js
- jQuery - Producttour.js
- jQuery - Megadropdown.js
- jQuery - Weather.js
- jQuery 有用资源
- jQuery - 问答
- jQuery - 快速指南
- jQuery - 有用资源
- jQuery - 讨论
jQuery - 替换元素
jQuery 提供了 **replaceWith()** 方法,用于在给定的 HTML 文档中用新内容替换现有的 HTML 内容。
jQuery replaceWith() 方法
jQuery 的 **replaceWith()** 方法会从 DOM 中移除内容,并在其位置插入新内容。
以下是 **replaceWith()** 方法的语法
$(selector).replaceWith(newContent);
replaceWith() 方法会移除与已移除节点关联的所有数据和事件处理程序。
概述
考虑以下 HTML 内容
<div class="container"> <h2>jQuery replaceWith() Method</h2> <div class="hello">Hello</div> <div class="goodbye">Goodbye</div> <div class="hello">Hello</div> </div>
现在,如果我们如下应用 **replaceWith()** 方法
$( ".hello" ).replaceWith("<h2>New Element</h2>" );
它将产生以下结果
<div class="container"> <h2>jQuery remove() Method</h2> <h2>New Element</h2> <div class="goodbye">Goodbye</div> <h2>New Element</h2> </div>
如果我们在 <div class="hello"> 内部有任何数量的嵌套元素,它们也将被移除。
示例
让我们尝试以下示例并验证结果
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<script src="https://tutorialspoint.com/jquery/jquery-3.6.0.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
$( ".hello" ).replaceWith("<h2>New Element</h2>" );
});
});
</script>
</head>
<body>
<div class="container">
<h2>jQuery replaceWith() Method</h2>
<div class="hello">Hello</div>
<div class="goodbye">Goodbye</div>
<div class="hello">Hello</div>
</div>
<br>
<button>Replace Element</button>
</body>
</html>
示例
以下示例将所有段落替换为 **Brilliant**。
<!doctype html>
<html lang="en">
<head>
<title>The jQuery Example</title>
<script src="https://tutorialspoint.com/jquery/jquery-3.6.0.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
$( "p" ).replaceWith( "<b>Brilliant</b>" );
});
});
</script>
</head>
<body>
<h2>jQuery replaceWith() Method</h2>
<p>Zara</p>
<p>Nuha</p>
<p>Ayan</p>
<button>Replace Element</button>
</body>
</html>
jQuery HTML/CSS 参考
您可以在以下页面获取所有 jQuery 方法以操作 CSS 和 HTML 内容的完整参考:jQuery HTML/CSS 参考。
广告
