jQuery replaceWith() 方法如何工作?
jqueryweb developmentfront end technology
replaceWith(content) 方法将所有匹配的元素替换为指定的 HTML 或 DOM 元素。这将返回刚刚被替换的 jQuery 元素,该元素已从 DOM 中移除。
以下是此方法使用的所有参数的说明 −
- content − 用于替换匹配元素的内容。
示例
您可以尝试运行以下代码来了解如何使用 replaceWith() 方法:
<html>
<head>
<title>jQuery replaceWith() method</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("div").click(function () {
$(this).replaceWith( ('<div class = "div"></div>') );
});
});
</script>
<style>
.div {
margin:10px;
padding:12px;
border:2px solid #666;
width:60px;
}
</style>
</head>
<body>
<p>Click on any square below to see the result:</p>
<div class = "div" style = "background-color:blue;">ONE</div>
<div class = "div" style = "background-color:green;">TWO</div>
<div class = "div" style = "background-color:red;">THREE</div>
</body>
</html>

