jquery replaceAll() 和 replaceWith() 方法详解
jquery replaceAll()方法,在编程过程中,有时会使用更改元素来操作 HTML 数据。这是许多人在处理错误消息或将元素更改为已处理数据时的做法。JQUERY 有两个内置函数query replaceWith() 和query replaceAll() 方法可以帮助您替换元素。在本教程中,我们将了解这些方法是如何工作的,以及如何轻松地将 HTML 元素替换为特定数据。
语法:
$(selector).replaceWith([CONTENT])
$(selector).replaceWith([CONTENT], FUNCTION ]
CONTENT – (REQUIRED) 指定要插入的内容。这也可以是 HTML 标签的形式。可能值包括 HTML 元素、JQUERY 对象、DOM 元素
。FUNCTION(INDEX) – (可选)指定返回要替换的内容的函数。 INDEX,返回在集合中找到的元素的索引位置。
代码
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("#btn-replace").click(function(){
$("h4:first").replaceWith("Lone Ranger");
});
});
</script>
</head>
<body>
<h4>first header</h4>
<h4>middle header</h4>
<h4>last header</h4>
<button type="button" id="btn-replace">Replace</button> </body> </html>
在上面的示例中,我们有三个 <h4> 标头。当您单击“Replace”按钮时,选择器仅将第一个标题与文本“第一个标题”更改为新文本“Lone Ranger”。replacewith() 方法适用于选择特定元素。但是,如果你想替换很多元素,你可以使用replaceAll()方法。
语法:
$([CONTENT]).replaceAll(selector)
CONTENT – (REQUIRED)指定要插入的内容。必须包含HTML标签
。SELECTOR – (REQUIRED)指定需要更改的元素。
代码
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("#btn-replace").click(function(){
$("<h1>CHANGED to H1</h1>").replaceAll("h5");
});
});
</script>
</head>
<body>
<button type="button" id="btn-replace">Replace</button>
<h5>First header.</h5>
<h5>Middle header</h5>
<h5>Last header</h5>
</body>
</html>
在本例中,我们更改了所有<h5>到的标头<h1>标题以及“已更改为H1”的文本。如果您计划操作大量HTML元素,那么replaceAll()方法非常有用。
常见问题FAQ
- 程序仅供学习研究,请勿用于非法用途,不得违反国家法律,否则后果自负,一切法律责任与本站无关。
- 请仔细阅读以上条款再购买,拍下即代表同意条款并遵守约定,谢谢大家支持理解!