繁体   English   中英

JQuery 将一个 HTML 标签替换为另一个

[英]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">

DOM 节点替换方法:

使用 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM