jquery怎么替换节点

jquery怎么替换节点,第1张

jquery怎么替换节点

jquery替换节点的方法:1、使用replaceWith(),语法“$(A).replaceWith(B)”,可用B节点来替换A节点;2、使用replaceAll(),语法“$(A).replaceAll(B)”,可用A节点来替换B节点。

本教程 *** 作环境:windows7系统、jquery1.10.2版本、Dell G3电脑。

在 jQuery 中,如果想要替换节点元素,我们用 replaceWith() 方法和 replaceAll() 方法来实现。

方法1:使用replaceWith()

在 jQuery 中,我们可以使用 replaceWith() 方法来将所选元素替换成其他元素。

语法:

$(A).replaceWith(B)

表示用 B 来替换 A。注:A和B都要是包含HTML标签的内容

示例:

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<script src="js/jquery-1.10.2.min.js"></script>
		<script>
			$(function() {
				$("button").click(function() {
					$("p").replaceWith("<div><b>Hello world!</b></div>")
				})
			})
		</script>
	</head>
	<body>
		<p>这是一个段落。</p>
		<p>这是另一个段落。</p>
		<br><button>将p节点替换为div节点</button>
	</body>
</html>

方法2:使用replaceAll()

在 jQuery 中,replaceAll() 和 replaceWith() 这两个方法功能虽然相似,都是将某个元素替换成其他元素,但是两者的 *** 作对象是颠倒的。

语法

$(A).replaceAll(B)

表示用 A 来替换 B。

示例:

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<script src="js/jquery-1.10.2.min.js"></script>
		<script>
			$(function() {
				$("button").click(function() {
					$("<div style='color:red;'>Hello world!</div>").replaceAll("p");
				})
			})
		</script>
	</head>
	<body>
		<p>这是一个段落。</p>
		<p>这是另一个段落。</p>
		<br><button>将p节点替换为div节点</button>
	</body>
</html>

【推荐学习:jQuery视频教程、web前端视频】

以上就是jquery怎么替换节点的详细内容,

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/731540.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-27
下一篇 2022-04-27

发表评论

登录后才能评论

评论列表(0条)

保存