[英]convert anchor tag to embed in jquery
我想将带有嵌入标签和 href 的 href 中包含 .pdf 的锚点转换为 src
<a href="www.google.com/pdf">Hello this is test</a>
这需要在嵌入标签中更改:如下输出
<embed src="www.google.com/pdf">
要实现此目的,请使用replaceWith()
。 为返回新内容的方法调用提供一个函数,如下所示:
$('a').replaceWith(function() { return `<embed src="${this.href}" />`; });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a href="https://www.google.com/pdf">Hello this is test</a>
请注意,您需要在绝对 URL 中包含协议。 以www
开头是行不通的。
当您不想要 jQuery 时,这是一个纯 JavaScript 解决方案:
const a = document.querySelector('a');
const e = document.createElement('embed');
e.setAttribute('src', a.href)
const aParent = a.parentElement;
const aNextSibling = a.nextElementSibling;
if (aNextSibling) {
aParent.insertBefore(e, aNextSibling);
} else {
aParent.appendChild(e);
}
a.remove();
只需替换outerHTML 。
$('a').each(function () {
if (this.href.indexOf('pdf')) { // checks whether href contains pdf
this.outerHTML = "<embed src=" + this.href + ">";
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.