PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

jquery怎么替换节点

青灯夜游
青灯夜游 原创
2022-04-22 13:06:36 3608浏览

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>

1.gif

方法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=&#39;color:red;&#39;>Hello world!</div>").replaceAll("p");
				})
			})
		</script>
	</head>
	<body>
		<p>这是一个段落。</p>
		<p>这是另一个段落。</p>
		<br><button>将p节点替换为div节点</button>
	</body>
</html>

2.gif

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

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。