- jQuery 教程
- jQuery - 首頁
- jQuery - 路線圖
- jQuery - 概述
- jQuery - 基礎
- jQuery - 語法
- jQuery - 選擇器
- jQuery - 事件
- jQuery - 屬性
- jQuery - AJAX
- jQuery DOM 操作
- jQuery - DOM
- jQuery - 新增元素
- jQuery - 刪除元素
- jQuery - 替換元素
- jQuery CSS 操作
- jQuery - CSS 類
- jQuery - 尺寸
- jQuery - CSS 屬性
- jQuery 效果
- jQuery - 效果
- jQuery - 動畫
- jQuery - 鏈式呼叫
- jQuery - 回撥函式
- jQuery 遍歷
- jQuery - 遍歷
- jQuery - 遍歷祖先節點
- jQuery - 遍歷後代節點
- jQuery UI
- jQuery - 互動
- jQuery - 小部件
- jQuery - 主題
- jQuery 參考
- jQuery - 選擇器
- jQuery - 事件
- jQuery - 效果
- jQuery - HTML/CSS
- jQuery - 遍歷
- jQuery - 雜項
- jQuery - 屬性
- jQuery - 工具函式
- jQuery 外掛
- jQuery - 外掛
- jQuery - PagePiling.js
- jQuery - Flickerplate.js
- jQuery - Multiscroll.js
- jQuery - Slidebar.js
- jQuery - Rowgrid.js
- jQuery - Alertify.js
- jQuery - Progressbar.js
- jQuery - Slideshow.js
- jQuery - Drawsvg.js
- jQuery - Tagsort.js
- jQuery - LogosDistort.js
- jQuery - Filer.js
- jQuery - Whatsnearby.js
- jQuery - Checkout.js
- jQuery - Blockrain.js
- jQuery - Producttour.js
- jQuery - Megadropdown.js
- jQuery - Weather.js
- jQuery 有用資源
- jQuery - 問題與解答
- jQuery - 快速指南
- jQuery - 有用資源
- jQuery - 討論
jQuery replaceWith() 方法
replaceWith() 方法用於將匹配元素集中的每個元素替換為指定的新內容。換句話說,它會從 DOM 中移除匹配的元素,並在其位置插入新內容。
replaceWith() 方法可以與其他 jQuery 方法鏈式呼叫。
語法
以下是 jQuery 中 replaceWith() 方法的語法:
$(selector).replaceWith(content,function(index))
引數
此方法接受以下引數:
- content: 要插入的內容。它可以是 HTML、jQuery 物件或 DOM 元素。
- function(index): 返回要替換所選元素內容的函式。
- index: 匹配元素集中元素的位置。
示例 1
在下面的示例中,我們使用 replaceWith() 方法將段落元素替換為新的標題元素:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
$("p").replaceWith("<h2>Replaced with a heading.</h2>");
})
});
</script>
</head>
<body>
<p>This is a paragraph.</p>
<button>Click to replace</button>
</body>
</html>
當我們點選按鈕時,新的標題元素將替換選定的段落元素。
示例 2
在這個示例中,我們使用 replaceWith() 方法替換列表中的一個項:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
$(".item").replaceWith("<li>Replaced item</li>");
})
});
</script>
</head>
<body>
<ul>
<li class="item">Item 1</li>
<li>Item 2</li>
</ul>
<button>Click to replace</button>
</body>
</html>
點選按鈕後,將觸發 replaceWith(),新的列表項將替換具有名為“item”的類的現有列表項。
示例 3
在這裡,我們使用可選的函式引數將每個段落元素替換為一個新的“div”元素,其中包含指示原始段落位置(索引號)和內容的訊息:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function(){
$("p").replaceWith(function(index, oldHtml) {
return "<div>Replaced paragraph " + (index + 1) + ": " + oldHtml + "</div>";
});
})
});
</script>
</head>
<body>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
<p>This is the third paragraph.</p>
<button>Click to replace</button>
</body>
</html>
執行上述程式後,所有段落元素都將被替換為一個新的 div 元素,指示段落元素的索引位置。
jquery_ref_html.htm
廣告
