繁体   English   中英

从定位标记中删除默认网址

[英]Remove the default url from anchor tag

我有以下代码,该代码输入用户的链接并使用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。 我不想要这些默认网址。 我该怎么办?

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

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

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

您可能需要在开头添加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> 

暂无
暂无

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

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