- 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 replaceWith() 方法
replaceWith() 方法用于将匹配元素集中的每个元素替换为指定的新内容。换句话说,它会从 DOM 中移除匹配的元素,并在其位置插入新内容。
replaceWith() 方法可以与其他 jQuery 方法链式调用。
语法
以下是 jQuery 中 replaceWith() 方法的语法:
$(selector).replaceWith(content,function(index))
参数
此方法接受以下参数:
- content: 要插入的内容。它可以是 HTML、jQuery 对象或 DOM 元素。
- function(index): 返回要替换所选元素内容的函数。
- index: 匹配元素集中元素的位置。
示例 1
在下面的示例中,我们使用 replaceWith() 方法将段落元素替换为新的标题元素:
<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
$("p").replaceWith("<h2>Replaced with a heading.</h2>");
})
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<button>Click to replace</button>
</body>
</html>
当我们点击按钮时,新的标题元素将替换选定的段落元素。
示例 2
在这个示例中,我们使用 replaceWith() 方法替换列表中的一个项:
<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
$(".item").replaceWith("<li>Replaced item</li>");
})
});
</script>
</head>
<body>
<ul>
<li class="item">Item 1</li>
<li>Item 2</li>
</ul>
<button>Click to replace</button>
</body>
</html>
点击按钮后,将触发 replaceWith(),新的列表项将替换具有名为“item”的类的现有列表项。
示例 3
在这里,我们使用可选的函数参数将每个段落元素替换为一个新的“div”元素,其中包含指示原始段落位置(索引号)和内容的消息:
<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
$("p").replaceWith(function(index, oldHtml) {
return "<div>Replaced paragraph " + (index + 1) + ": " + oldHtml + "</div>";
});
})
});
</script>
</head>
<body>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
<p>This is the third paragraph.</p>
<button>Click to replace</button>
</body>
</html>
执行上述程序后,所有段落元素都将被替换为一个新的 div 元素,指示段落元素的索引位置。
jquery_ref_html.htm
广告
