【问题标题】:Remove hyperlink but keep text?删除超链接但保留文本?
【发布时间】:2023-03-31 04:20:02
【问题描述】:
<a href="http://www.website.com/something" title="Show Profile">Mentalist</a>

每当超链接的标题为“显示配置文件”时,我想删除超链接并仅将其替换为文本。

所以不是

<a href="http://www.website.com/something" title="Show Profile">Mentalist</a>

我只想拥有Mentalist

知道如何解决这个问题吗?

【问题讨论】:

    标签: javascript jquery hyperlink


    【解决方案1】:

    这应该可行:

    $('a[title="Show Profile"]').contents().unwrap();
    

    这里是 Fiddle 的证明。

    【讨论】:

    • unwrap() 非常简洁。只是为了完整起见,这里有一个也应该有效的替代解决方案: $("a[title='Show Profile']").replaceWith(function() { return $(this).contents(); });
    • 真聪明! +10
    【解决方案2】:

    这样就可以了:

    <a href="http://www.website.com/something" title="Show Profile">Mentalist</a>
    <a href="http://www.website.com/something" title="Something Else">Mentalist</a>
    
    <script type="text/javascript">
    $("a[title='Show Profile']").each(function(){
        $(this).replaceWith($(this).text());
    });
    </script>
    

    它应该只替换第一个链接。

    【讨论】:

    【解决方案3】:

    要对多个类的链接执行此操作,

    $("a.className1, a.className2").contents().unwrap();
    

    【讨论】:

      【解决方案4】:

      Vanilla JavaScript 方式(而不是 jQuery)删除超链接但保留文本:

      const links = document.querySelectorAll('a[title="Show Profile"]')
      
      links.forEach(link => {
          const el = document.createElement('span')
          el.textContent = link.textContent
          link.parentNode.replaceChild(el, link)
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-15
        • 2013-03-08
        • 1970-01-01
        • 2018-04-03
        • 1970-01-01
        • 2017-02-05
        • 2011-07-18
        • 1970-01-01
        相关资源
        最近更新 更多