繁体   English   中英

如何在不替换内容的情况下替换jquery中的html标签?

[英]how to replace html tag in jquery without replace content?

我想知道如何在不替换内容的情况下更改 HTML 标记。 我做了这样的事情:

 $('#test > span').replaceWith('<div>' + $('#test > span').html() +'</div>');
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="test"> <span>hello</span> <span>hello2</span> <span>hello3</span> </div>

有效,但仍显示第一个值(查看代码片段)。 我想我需要将.replaceWith()$(this)合并,但我不能完全做到。

要执行您的要求,您可以将函数传递给replaceWith() 此函数接受两个参数,当前元素的索引及其内容,并返回新元素以进行替换。 因此,您可以使用第二个参数来更改父标签,同时保持相同的内容,如下所示:

 $('#test > span').replaceWith((i, content) => `<div>${content}</div>`);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="test"> <span>hello</span> <span>hello2</span> <span>hello3</span> </div>

您还可以使用 RegExp 将 innerHTML 中的所有<span></span>替换为<div></div>

 // jQuery version $('#btnReplaceHTML').click(() => { const re = /(<\\/?)span(>)/gm $('#test').html($('#test').html().replace(re, '$1div$2')); }) /* // "Vanilla" JavaScript version document.getElementById('btnReplaceHTML').addEventListener('click', () => { const re = /(<\\/?)span(>)/gm const elem = document.getElementById('test'); elem.innerHTML = elem.innerHTML.replace(re, '$1div$2'); }); */
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="test"> <span>hello</span> <span>hello2</span> <span>hello3</span> </div> <button id="btnReplaceHTML">replace HTML</button>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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