013_替换元素
1. replaceWith()方法
1.1. replaceWith(content)方法用指定的html內容或元素(元素本身和子元素)替換每一個匹配元素。
1.2. 語法
$(selector).replaceWith(content)1.3. 參數
1.4. 使用函數來替換元素
1.4.1. replaceWith(function(index, origHtml))方法使用函數替換所有匹配元素中指定坐標的元素。
1.4.2. 語法
$(selector).replaceWith(function(index, origHtml))1.4.3. 參數
1.5. 如果replaceWith()方法用于已有元素, 這些元素會被從當前位置移走, 然后替換匹配元素。
1.6. 例子
1.6.1. 代碼
<!DOCTYPE html> <html><head><meta charset="utf-8" /><title>replaceWith替換元素</title><script type="text/javascript" src="jquery.js"></script><script type="text/javascript">$(document).ready(function(){$('#btn1').click(function(){$("p").replaceWith("<p>語法<br />$(selector).replaceWith(content)</p>");});$('#btn2').click(function(){$("p").replaceWith(function(index, origHtml) {return "<p>語法<br />$(selector).replaceWith(function(index, origHtml))</p>";});});$('#btn3').click(function(){$("p").replaceWith($('h2'));});});</script></head><body><h2><i>replaceWith()</i>方法替換元素</h2><div style="background-color: red; width: 600px; height: 100px;"><p>replaceWith(content)方法用指定的html內容或元素(元素本身和子元素)替換每一個匹配元素。</p></div><div style="background-color: green; width: 600px; height: 100px;"><p>replaceWith(function(index, origHtml))方法使用函數替換所有匹配元素中指定坐標的元素。</p></div> <br /><button id="btn1">replaceWith替換元素</button> <button id="btn2">replaceWith使用函數來替換元素</button><button id="btn3">使用已存在元素替換</button></body> </html>1.6.2. 效果圖
2. replaceAll()方法
2.1. replaceAll()方法用指定的html內容或元素(元素本身和子元素)替換每一個匹配元素。
2.2. replaceAll()與replaceWith()作用相同。差異在于語法: 內容和選擇器的位置, 以及replaceWith()能夠使用函數進行替換。
2.3. 語法
$(content).replaceAll(selector)2.4. 參數
2.5. 例子
2.5.1. 代碼
<!DOCTYPE html> <html><head><meta charset="utf-8" /><title>replaceAll替換元素</title><script type="text/javascript" src="jquery.js"></script><script type="text/javascript">$(document).ready(function(){$('#btn1').click(function(){var txt = document.createElement("p");txt.innerHTML = "以DOM創建新元素.";$(txt).replaceAll("p");});});</script></head><body><div style="background-color: red; width: 600px; height: 100px;"><p>replaceAll()方法用指定的html內容或元素(元素本身和子元素)替換每一個匹配元素。</p></div> <div style="background-color: green; width: 600px; height: 100px;"><p>replaceAll()與replaceWith()作用相同。差異在于語法: 內容和選擇器的位置, 以及replaceWith()能夠使用函數進行替換。</p></div><br /><button id="btn1">replaceAll替換元素</button></body> </html>2.5.2. 效果圖
總結