简体   繁体   English

用 a 标签包装 span 标签,其 href 目标与 span 的文本相同

[英]wrapping a span tag with an a tag with a href target same as the text of the span

my document has many span tags like the following:我的文档有许多跨度标签,如下所示:

<span class='myClass'>aaa</span>

I would like to turn each of them into the following:我想将它们中的每一个变成以下内容:

<a href="http://www.example.com/aaa" onclick="myfunc();"><span class='myClass'>aaa</span></a>

Is there a way to do this?有没有办法做到这一点? could be plain js or jquery (3.1.1)可以是纯 js 或 jquery (3.1.1)

Thank you in advance先感谢您

Use this:用这个:

const els=document.querySelectorAll("span.myClass");
els.forEach((el)=>{
   const t=el.textContent;
   const aEl=document.createElement("a");
   aEl.href=`http://example.com/${t}`;
   aEl.appendChild(el.cloneNode(true))
   el.parentElement.insertBefore(aEl,el);
   el.remove()
})

With jQuery, you can iterate all .myClass elements using .each() , then wrap them using .wrap()使用 jQuery,您可以使用.each()迭代所有.myClass元素,然后使用.wrap()包装它们

 $(".myClass").each( function() { $(this).wrap('<a href="http://www.example.com/' + $(this).text() + '" onclick="myfunc();" />'); }); console.log($(".myClass").parent())
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <span class='myClass'>aaa</span> <span class='myClass'>bbb</span> <span class='myClass'>ccc</span> <span class='myClass'>ddd</span>

https://api.jquery.com/wrap/ https://api.jquery.com/wrap/

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

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