码迷,mamicode.com
首页 > Web开发 > 详细

jQuery的replaceWith()函数用法详解

时间:2015-07-17 15:38:18      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

replaceWith,替换元素

replaceWith() 方法将选择的元素的内容替换为其他内容。

我们先在先看一个实例

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.51texiao.cn/" />
<title>无标题</title>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
       $("button").click(function(){
           $("p").replaceWith("<b>hello</b>");
           //将p元素里面的内容替换为"<b>hello</b>"
       });
    });
</script>
</head>
 
<body>
    <p>1111111111111111111111</p>
    <button>click</button>
</body>
</body>
</html>

可能很多朋友看不明白,下面我来一一介绍。

jQuery中,有一个强大的替换函数replaceWith(),使用非常简单,如:

页面有如下p标签

<body>
    <p>哈哈</p>
    <p>哈哈</p>
    <p>哈哈</p>
    <p>哈哈</p>
    <button>click</button>
</body>

把所有p标签替换为“##”

<script type="text/javascript">
    $(document).ready(function(){
       $("button").click(function(){
           $("p").replaceWith("##");
           //将p元素替换成##"
       });
    });
</script>

执行后的结果:

技术分享

替换标签

利用这个replaceWith,我们可以把所有p标签替换为b标签,内容不变:

 $("button").click(function(){
          $(‘p‘).each(function(){
            $(this).replaceWith(‘<b>‘+$(this).html()+‘</b>‘)
          })
       });

结果

技术分享

这就替换了!

多语言网站可以利用这个函数轻松完成

如果你开发的是一个多语言的网站,甚至可以利用这个特性,比如,在你需要翻译的文字上加上i标签,然后遍历翻译替换。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.51texiao.cn/" />
<title>无标题</title>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
      var translate={
        苹果:apple,
        电脑:PC
      };
       $("button").click(function(){
          $(i).each(function(){
            $(this).replaceWith(translate[$(this).html()]);
          })
       });
    });
</script>
</head>
 
<body>
    <p><i>苹果</i></p>
    <p><i>电脑</i></p>
        <button>click</button>
</body>
</body>
</html>

replaceWith和replaceAll

相同点:他们二个都可以进行,查找替换

不同点:写法不同,反正我是没有发现,他们二个有什么功能上的不同。

 

 

jQuery的replaceWith()函数用法详解

标签:

原文地址:http://www.cnblogs.com/eveblog/p/4654459.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!