简体   繁体   English

使用 jQuery 将锚标记转换为纯文本

[英]Converting an anchor tag to plain text with jQuery

I am running into a problem with my output of an HTML-to-PDF process where my anchor tags that contain the tel: protocol are kicking back errors when clicked.我的 HTML 到 PDF 进程的 output 遇到问题,其中包含tel:协议的锚标记在单击时会出现错误。 It turns out that these hrefs are being seen as relative URLs unlike how mailto: is recognized as it's own thing.事实证明,这些hrefs被视为相对 URL,与mailto:被识别为它自己的东西不同。

I figure that if I can target these elements directly, I could take their content, hide the <a> tag entirely and only display the content in a new element.我想如果我可以直接定位这些元素,我可以获取它们的内容,完全隐藏<a>标签,只在新元素中显示内容。 Maybe this is overthinking it?或许这是想太多了吧?

Here's where I went: https://jsfiddle.net/BIPC_Sydor/yL8suwno/1/这是我去的地方: https://jsfiddle.net/BIPC_Sydor/yL8suwno/1/

I wanted to try and target each instance of an <a> tag within a specific div (class of menu).我想尝试在特定的 div(菜单类)中定位<a>标记的每个实例。 Then copy the content of each instance into a new <p> tag (class of pdf).然后将每个实例的内容复制到一个新的<p>标记(pdf 类)中。 From there I could hide the old <a> and stylize the new <p> .从那里我可以隐藏旧的<a>并将新的<p>风格化。 Unfortunately, it's outputting both anchors' content in more instances that I expected.不幸的是,它在我预期的更多实例中输出了两个锚点的内容。 Is this doable?这是可行的吗?

My code from the fiddle:我的小提琴代码:

HTML HTML

<div class="menu">
  <a href="page.html">Page 1</a>
  <a href="page2.html">Page 2</a>
</div>

JS JS

$( '.menu a' ).each(function( i ) {
  var res = $('.menu a').text();
  $('.menu a').after('<p class="pdf">'+ res +'</p>');
});

You can use after(function) and chain hide() to hide the <a> as well您也可以使用after(function)和 chain hide()来隐藏<a>

 $('.menu a').after(function() { return $('<p>', {class: 'pdf', text: $(this).text()}) }).hide()
 p.pdf { color: red }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="menu"> <a href="page.html">Page 1</a> <a href="page2.html">Page 2</a> </div>

use value as well in your each() method, and use the value reference to update nodes, else it will update all the nodes.在 each() 方法中也使用value ,并使用值引用来更新节点,否则它将更新所有节点。

$( '.menu a' ).each(function( index,value ) {
  var res = $(value).text(); // value is for current iteration
  $(value).after('<p class="pdf">'+ res +'</p>');
  // do something else...
});


Reference here: https://api.jquery.com/jquery.each/参考这里: https://api.jquery.com/jquery.each/

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

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