![](/img/trans.png)
[英]How to reverse effects of jQuery replaceWith function on HTML select tag?
[英]JQuery replaceWith one HTML tag with another
我有一個img
選項卡,如下所示:
<img class="media-1200px" src="https://images.pexels.com/photos/414612/pexels-photo-414612.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500">
我使用 .replaceWith() $(this).replaceWith("<div>" + $(this).html() + "</div>");
並期待如下代碼:
<div class="media-1200px" src="https://images.pexels.com/photos/414612/pexels-photo-414612.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" </div>
但不知何故我得到了:
<div></div>
請看一下我的代碼:
$('img').each(function() { $(this).replaceWith("<div>" + $(this).html() + "</div>"); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <img class="media-1200px" src="https://images.pexels.com/photos/414612/pexels-photo-414612.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500">
使用 vanilla JavaScript,您只需使用outerHTML()屬性將元素作為字符串檢索,只需使用replace()方法將“img”替換為“div”,然后將<img>
元素替換為您的<div>
您的 DOM(不確定為什么,因為 div 不能真正利用src
屬性),只需使用createContextualFragment()將當前檢索到的分配給div
變量的字符串轉換為 DOM 節點,然后使用replaceNode()方法替換img
節點與 DOM 中的div
節點。
檢查並運行以下代碼片段或打開此JSFiddle以獲得上述方法的實際示例:
const img = document.querySelector("img"); const div = img.outerHTML.replace("img", "div"); let newDiv = document.createRange().createContextualFragment(div); img.parentNode.replaceChild(newDiv, img);
<img class="media-1200px" src="https://images.pexels.com/photos/414612/pexels-photo-414612.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500">
注意您必須檢查代碼片段沙箱或 JSFiddle 沙箱才能看到<img/>
元素替換為<div>
元素。
另一種方法(從上面 Barmar 的 jQuery 解決方案中得到這個想法)是創建一個新的 div 元素,然后使用attributes屬性和setAttributes()方法將<img>
元素的屬性克隆到新的<div>
元素像這樣:
const img = document.querySelector("img"); const newDiv = document.createElement("div"); [...img.attributes].forEach(({name, value}) => newDiv.setAttribute(name, value) ); img.parentNode.replaceChild(newDiv, img);
<img class="media-1200px" src="https://images.pexels.com/photos/414612/pexels-photo-414612.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500">
NB同樣,您必須檢查代碼片段沙箱或 JSFiddle 沙箱才能看到<img/>
元素替換為<div>
元素。
試試這個
$('img').each(function() {
$(this).replaceWith("<div with="100px"> + $(this).html() + "</div>");
});
你應該設置屬性寬度來可視化一個 div。
您不能使用.html()
來獲取元素本身的 HTML。 即使可以,因為您將 HTML 放在<div>
和</div>
,它會將圖像嵌套在 DIV 中(就像.wrap()
那樣),而不是將圖像屬性放入 DIV 本身。
您需要創建 DIV 元素並將屬性復制到它。
$('img').replaceWith(function() { return $("<div>", { "class": $(this).attr("class"), css: { "background-image": `url(${$(this).attr("src")})` } }); });
div.media-1200px { width: 1200px; height: 100px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <img class="media-1200px" src="https://images.pexels.com/photos/414612/pexels-photo-414612.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.