DOM替换replaceWith()和replaceAll()
发布时间: 2018-06-14      作者:admin    浏览:189 次

.replaceWith( newContent ):用提供的内容替换集合中所有匹配的元素并且返回被删除元素的集合

简单来说:用$()选择节点A,调用replaceWith方法,传入一个新的内容B(HTML字符串,DOM元素,或者jQuery对象)用来替换选中的节点A

<script type="text/javascript" src="http://ayued.aykj.wang/subsiteSrc/mainpc/js/jquery-1.11.2.min.js"></script>
<script type="text/javascript">
	function clearUrl(){
		$(".body a").each(function(){
			var text=$(this).text()
			$(this).replaceWith(text);
		});
	}
</script>
<html>
<head>
<script type="text/javascript" src="http://ayued.aykj.wang/subsiteSrc/mainpc/js/jquery-1.11.2.min.js"></script>
<script type="text/javascript">
	function clearUrl(){
		$(".body a").each(function(){
			var text=$(this).text()
			$(this).replaceWith(text);
		});
	}
</script>
</head>
 
<body>
    <div class="body">
      <div><a href="http://corp.sina.com.cn/chn/">新浪简介</a> ┊ <a href="http://corp.sina.com.cn/eng/">About Sina</a> ┊ <a href="http://emarketing.sina.com.cn/">广告服务</a> ┊ <a href="http://www.sina.com.cn/contactus.html">联系我们</a> ┊ <a href="http://career.sina.com.cn/">诚聘英才</a> ┊ <a href="http://www.sina.com.cn/intro/lawfirm.shtml">网站律师</a> ┊ <a href="http://english.sina.com/">SINA English</a> ┊ <a href="https://login.sina.com.cn/signup/signup.php">注册</a> ┊ <a href="http://help.sina.com.cn/">产品答疑</a></div>
      <p>Copyright ©1996-2018 SINA Corporation, All Rights Reserved</p>
      <br>
    </div>
    <button onclick="clearUrl();">清楚链接</button>
</body>
</html>

总结:

.replaceAll()和.replaceWith()功能类似,主要是目标和源的位置区别
.replaceWith()与.replaceAll() 方法会删除与节点相关联的所有数据和事件处理程序
.replaceWith()方法,和大部分其他jQuery方法一样,返回jQuery对象,所以可以和其他方法链接使用
.replaceWith()方法返回的jQuery对象引用的是替换前的节点,而不是通过replaceWith/replaceAll方法替换后的节点

分享到:

朋友圈

新浪微博

QQ空间

豆瓣网

QQ好友