您的位置:首页 > Web前端 > JQuery

jQuery的replaceWith()函数用法详解

2015-07-17 14:48 701 查看
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

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

不同点:写法不同,反正我是没有发现,他们二个有什么功能上的不同。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: