jQuery中的replaceWith和replaceAll方法

在jQuery中有两个方法可以执行对标签的替换操作,replaceWith()和replaceAll()方法: 

replaceWith() :将所有匹配的元素替换成指定的HTML或DOM元素。

replaceAll(selector):用匹配的元素替换掉所有 selector匹配到的元素。

在如下的代码中,首先使用标签选择器获取span,b,i标签,然后调用replaceWith()方法将其替换为h3标签。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<script src="js/jquery-3.3.1.js"></script>
	</head>
	<body>
		<span>123</span>
		<b>123</b>
		<i>123</i>
		
		<script>
			$("span,b,i").replaceWith("<h3>HelloWorld</h3>");
		</script>
	</body>
</html>

 而这段代码中,是使用h3标签调用replaceAll()方法,在参数列表中传入span,b,i标签的jQuery对象。两个程序的运行结果如下:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<script src="js/jquery-3.3.1.js"></script>
	</head>
	<body>
		<span>123</span>
		<b>123</b>
		<i>123</i>
		
		<script>
			$("<h3>HelloWorld</h3>").replaceAll("span,b,i");
		</script>
	</body>
</html>

发布了99 篇原创文章 · 获赞 93 · 访问量 5214

猜你喜欢

转载自blog.csdn.net/DangerousMc/article/details/103016600