首页 > 解决方案 > 从锚标记中删除默认 url

问题描述

我有以下代码,它输入来自用户的链接并创建一个anchor标签href = link

<html>
<head>
    <title>Page Title</title>
    <style>
        #text-input {
            border-left: 4px solid green;
            text-indent: 12px;
        }
    </style>
</head>
<body>
    <p>Enter a link</p>
    <div id="text-input" contenteditable="true"></div>
    
    <script>
      let div = document.getElementById('text-input');
      let anchor;

      div.addEventListener('blur', event => {
        let text = div.innerText;
        div.innerText = '';
        anchor = document.createElement('a');
        div.appendChild(anchor);
        anchor.innerText = text;
        anchor.href = text;
        
        // The below line logs the actual link of the anchor tag
        console.log(anchor.href);
      });
    </script>
</body>
</html>

问题

当我为 href 分配链接的值时,链接似乎也包含一些默认的网站 url。我不想要那些默认网址。我应该怎么办?

标签: javascripthtmlanchor

解决方案


也许这是相对网址的问题?如果文本没有,请在文本开头添加“http://”。


推荐阅读