如何使用 jQuery 替換 DOM 元素為指定的 HTML 或 DOM 元素?
要使用 jQuery 替換 DOM 元素為指定的 HTML 或 DOM 元素,請使用 replaceWith() 方法。replaceWith (content) 方法將所有匹配的元素替換為指定的 HTML 或 DOM 元素。這將返回剛剛被替換的 jQuery 元素,該元素已被從 DOM 中移除。
示例
你可以嘗試執行以下程式碼以瞭解如何用指定的 HTML 或 DOM 元素替換 DOM 元素
<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:yellow;">ONE</div>
<div class = "div" style = "background-color:maroon;">TWO</div>
<div class = "div" style = "background-color:blue;">THREE</div>
</body>
</html>
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP