【问题标题】:Remove the default url from anchor tag从锚标记中删除默认 url
【发布时间】:2018-09-23 15:43:25
【问题描述】:

我有以下代码输入用户的 链接 并使用 href = link 创建一个 anchor 标记

<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。我不想要那些默认网址。我该怎么办?

【问题讨论】:

  • “链接包含一些默认的网站网址”,您能详细说明一下吗?
  • @Arvind 尝试输入任何网站链接,然后您会在控制台中输入链接之前看到一些默认网址。

标签: javascript html anchor


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    根据您的默认要求,您可以将 https 或 http 附加到输入数据。

     anchor.innerText = text;       
                if(text.indexOf('http://')!=0 || text.indexOf('https://')!=0){
                    text = "http://"+text;  //default http(or) https
                }
                 anchor.href = text;
    

    【讨论】:

      【解决方案3】:

      您可能需要在开头添加 http:// 或 https://。

      <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 = 'http://'+text;
              
              // The below line logs the actual link of the anchor tag
              console.log(anchor.href);
            });
          </script>
      </body>
      </html>

      【讨论】:

        猜你喜欢
        • 2013-12-10
        • 2022-06-30
        • 2019-03-13
        • 1970-01-01
        • 2021-06-27
        • 2011-10-08
        • 2021-07-10
        • 2013-12-05
        相关资源
        最近更新 更多