【问题标题】:How to remove hyper link from html method [duplicate]如何从html方法中删除超链接[重复]
【发布时间】:2014-10-03 13:58:01
【问题描述】:

请浏览下面的代码并帮助我,如何从 html 方法中删除超链接。 我想要在 footercontent 变量中以 HTML 格式的最终​​输出。

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        var footercontent = $('footer').html();
        alert(footercontent); 
    });
    </script>
</head>
<body>

    <footer>
        <a href="#">Site Map</a> | <a href="#">Privacy statement</a> | <a href="#">Tutorials</a>
        <p>Fotoer contetn 1</p>
        <p>Footer content 2</p>
        <p>Footer content 3</p>
        <p>Footer content 4</p>

    </footer>

</body>
</html>

【问题讨论】:

  • 你想让链接只是文本,还是完全删除链接的存在?
  • 是的,我想要这些链接只是文本

标签: javascript jquery html css


【解决方案1】:

你可以使用jquery.replaceWith()

$("footer > a").replaceWith(function(){
    return $( this ).contents();
}); 

fiddle

【讨论】:

  • 感谢它的工作正常和预期。
  • 比你原来的答案好多了。
  • @epascarello 原始答案是因为我认为他想删除 a 元素。
  • 嗨,亚历克斯,我希望最终以一个具有相同格式的变量输出。我将在打印功能中使用该变量
【解决方案2】:

循环使用replaceWith或者使用replaceWith中的函数

$("a").each(
    function() {
         var anc = $(this);
         anc.replaceWith(anc.text());   
    }
);

【讨论】:

    【解决方案3】:

    正则表达式是你所需要的......

    取自Regex in Javascript to remove links

      mystr = "check this out <a href='http://www.google.com'>Click me</a>. cool, huh?";
    alert(mystr.replace(/<a\b[^>]*>(.*?)<\/a>/i,""));
    

    【讨论】:

    • 您应该添加评论以将问题标记为重复...
    • 你不应该在 HTML 上使用正则表达式
    猜你喜欢
    • 2021-06-20
    • 2021-09-13
    • 2020-10-30
    • 1970-01-01
    • 2018-10-28
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    相关资源
    最近更新 更多